Rumah  >  Artikel  >  hujung hadapan web  >  Selectors API_html/css_WEB-ITnose

Selectors API_html/css_WEB-ITnose

WBOY
WBOYasal
2016-06-21 08:52:50996semak imbas

HTML5向Web API新引入了

document.querySelectordocument.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>
Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn