Home > Web Front-end > HTML Tutorial > Selectors API_html/css_WEB-ITnose

Selectors API_html/css_WEB-ITnose

WBOY
Release: 2016-06-21 08:52:50
Original
1061 people have browsed it

HTML5向Web API新引入了

document.querySelectordocument.querySelectorAll
Copy after login

两个方法用来更方便地从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>
Copy after login
<!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>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template