querySelectorAll和getElementsByTagName有什么区别? [英] What is the difference between querySelectorAll and getElementsByTagName?
问题描述
我想知道JavaScript中选择元素的两种不同语法.
I was wondering about two different syntax of selecting element in JavaScript.
假设我要从当前文档中选择所有div,那么
suppose if I want to select all divs from current document then:
var divs = document.getElementsByTagName("div");
alert("There are "+divs.length+" Divs in Document !");
可以正常工作.但是还有另一种方式,例如:
Will work fine. But there is also another way of doing so, like:
var divs = document.querySelectorAll("div");
alert("There are "+divs.length+" Divs in Document !");
两者都以相同方式工作时.它们之间有什么区别?
When both of them works in the same way. What's the difference between them ?
先谢谢了.我见过这样的问题,但他们不满足需要.
Thanks in advance. I've seen the questions like this but they didn't satisfied the need.
推荐答案
getElementsByTagName
仅根据标签名称选择元素. querySelectorAll
可以使用任何选择器,这使它具有更大的灵活性和功能,但它较新,因此对浏览器的支持也较弱.
getElementsByTagName
only selects elements based on their tag name. querySelectorAll
can use any selector which gives it much more flexibility and power, but it is newer and so has weaker browser support.
getElementsByTagName
可能更快,因为它更简单,但这不太可能对您所做的任何事情产生明显影响.
getElementsByTagName
is probably faster, since it is simpler, but that is unlikely to have a noticeable impact on anything you do with it.
这篇关于querySelectorAll和getElementsByTagName有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!