Selectors API

作者: IT小C | 来源:发表于2016-03-28 13:23 被阅读76次

    HTML5向Web API新引入了

    document.querySelector
    document.querySelectorAll
    

    两个方法用来更方便地从DOM选取元素,功能类似于jQuery的选择器。这使得在编写原生JavaScript代码时方便了许多。

    querySelector

    该方法返回满足条件的单个元素。按照深度优先和先序遍历的原则使用参数提供的CSS选择器在DOM进行查找,返回第一个满足条件的元素。

    querySelectorAll

    该方法返回所有满足条件的元素,结果是个nodeList集合。查找规则与前面所述一样。

    <!DOCTYPE html>
    <html>
        <body>
            <h3> h3 元素</h3>
            <h2> h2 元素</h2>
            <script>
                //querySelector会给所有元素的第一个元素加上样式
                document.querySelector("h2, h3").style.backgroundColor = "red";
            </script>
        </body>
    </html>
    
    <!DOCTYPE html>
    <html>
        <body>
            <h2> h2 元素</h2>
            <h3> h3 元素</h3>
            <script>
                //querySelectorAll获取所有元素,返回一个list集合
                var o2 = document.querySelectorAll("h2, h3");
                for(var i in o2){
                    o2[i].style.backgroundColor = "red"; 
                }
            </script>
        </body>
    </html>
    

    相关文章

      网友评论

        本文标题:Selectors API

        本文链接:https://www.haomeiwen.com/subject/kzujlttx.html