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>
    现在所有的元素都有$方法了。
     

     

  • 相关阅读:
    HDU 1312 Red and Black DFS(深度优先搜索) 和 BFS(广度优先搜索)
    HDU 1241 Oil Deposits DFS(深度优先搜索) 和 BFS(广度优先搜索)
    邮件推广工具
    aix-syslog
    能量点
    知识picture
    C中运算符
    stdio.h头文件中申明的基本函数
    字符串
    指针字符串
  • 原文地址:https://www.cnblogs.com/youxin/p/2739165.html
Copyright © 2011-2022 走看看