zoukankan      html  css  js  c++  java
  • dom querySelector

    element = document.querySelector(selectors);

    Returns the first element within the document (using depth-first pre-order traversal of the document's nodes) that matches the specified group of selectors.

    • element is an element object.
    • selectors is a string containing one or more CSS selectors separated by commas.

    In this example, the first element in the document with the class "myclass" is returned:
    varel = document.querySelector(".myclass");

    Returns null if no matches are found; otherwise, it returns the first matching element.

     

    还有一个相对应的方法:

    elementList = document.querySelectorAll(selectors);
    返回所有匹配的元素,放回结果是一个NodeList。 elementList is a non-live NodeList of element objects.

     

    Along the lines of other frameworks such as jQuery or Prototype, shortening the "querySelector" name can be convenient.

    function $ (selector, el) {
         if (!el) {el = document;}
         return el.querySelector(selector);
    }
    function $$ (selector, el) {
         if (!el) {el = document;}
         return el.querySelectorAll(selector);
         // Note: the returned object is a NodeList.
         // If you'd like to convert it to a Array for convenience, use this instead:
         // return Array.prototype.slice.call(el.querySelectorAll(selector));
    }
    alert($('#myID').id);

    Example:

     
    <h1>Test!</h1>
    <script>
    HTMLDocument.prototype.$ = function (selector) {
        return this.querySelector(selector);
    };
    alert(document.$('h1')); // [object HTMLHeadingElement]
    </script>
    现在所有的元素都有$方法了。
     

     

  • 相关阅读:
    反编译乱码对比
    ABP缓存写法
    AutoMapperHelper
    读取硬盘SN
    wpf用Prism里控件事件绑定mvvm
    ajax请求.net后台接收
    网站博客截取简介
    C# datetime.now.tostring("yyyy/MM/dd") 显示为yyyy-MM-dd的解决办法
    html5远程控制
    SmartThreadPool
  • 原文地址:https://www.cnblogs.com/youxin/p/2739165.html
Copyright © 2011-2022 走看看