javascript querySelectorAll 和 getElementsByTagName 有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18247289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the difference between querySelectorAll and getElementsByTagName?
提问by Vedant Terkar
I was wondering about two different syntax of selecting element in JavaScript.
我想知道在 JavaScript 中选择元素的两种不同语法。
suppose if I want to select all divs from current document then:
假设如果我想从当前文档中选择所有 div,那么:
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.
提前致谢。我见过这样的问题,但他们没有满足需求。
采纳答案by Quentin
getElementsByTagName
only selects elements based on their tag name. querySelectorAll
can use any selectorwhich gives it much more flexibility and power, but it is newer and so has weaker browser support.
getElementsByTagName
仅根据元素的标签名称选择元素。querySelectorAll
可以使用任何赋予它更多灵活性和功能的选择器,但它更新,因此浏览器支持较弱。
getElementsByTagName
is probably faster, since it is simpler, but that is unlikely to have a noticeable impact on anything you do with it.
getElementsByTagName
可能更快,因为它更简单,但这不太可能对你用它做的任何事情产生明显的影响。
回答by Artem G
Most answeres are wrong. Nicolae Olariu is the only, who answered correcly
大多数答案都是错误的。Nicolae Olariu 是唯一一个正确回答的人
Which one is faster? Why?
哪个更快?为什么?
are not the questions. The real question "How it works?"
不是问题。真正的问题“它是如何工作的?”
The main difference is in this example:
主要区别在此示例中:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Yandex</title>
</head>
<body>
<a href="((http://yandex.ru))">Яндекс</a>,
<a href="((http://yandex.com))">Yandex</a>
</body>
<script>
var elems1 = document.getElementsByTagName('a'), // return 2 lements, elems1.length = 2
elems2 = document.querySelectorAll("a"); // return 2 elements, elems2.length = 2
document.body.appendChild(document.createElement("a"));
console.log(elems1.length, elems2.length); // now elems1.length = 3!
// while elems2.length = 2
</script>
</html>
Because querySelectorAll returns a static (not live) list of elements.
因为 querySelectorAll 返回一个静态(非实时)元素列表。
回答by Nicolae Olariu
From MDN:
来自 MDN:
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.
返回文档中与指定选择器组匹配的第一个元素(使用文档节点的深度优先预序遍历)。
elements = element.getElementsByTagName(tagName)
Returns a list of elements with the given tag name. The subtree underneath the specified element is searched, excluding the element itself. The returned list is live, meaning that it updates itself with the DOM tree automatically. Consequently, there is no need to call several times element.getElementsByTagName with the same element and arguments.
返回具有给定标签名称的元素列表。搜索指定元素下的子树,不包括元素本身。返回的列表是实时的,这意味着它会自动使用 DOM 树更新自身。因此,无需使用相同的元素和参数多次调用 element.getElementsByTagName。
回答by devongovett
querySelector
also supports other CSS selectors such as "#id"
to get an element by id, and "input[type=text]"
to get all input elements with a type=text
attribute. See herefor more details.
querySelector
还支持其他 CSS 选择器,例如"#id"
通过 id 获取元素,以及"input[type=text]"
获取具有type=text
属性的所有输入元素。请参阅此处了解更多详情。
They would probably be about equally fast for simple queries like the one you asked about, but for advanced CSS selectors it is likely much faster (not to mention much less code to write) to use querySelectorAll
than applying some manual filtering yourself, which is why libraries like jQuery use querySelectorAll
when the browser supports it.
对于像您询问的那样的简单查询,它们可能同样快,但是对于高级 CSS 选择器,使用它可能querySelectorAll
比自己应用一些手动过滤要快得多(更不用说编写的代码要少得多),这就是库的原因就像 jQueryquerySelectorAll
在浏览器支持时使用。
回答by liwenkang
Here is an exampleabout the difference between querySelector and getElementsByTagName.
下面是一个关于 querySelector 和 getElementsByTagName 之间差异的示例。
In this example,the writer choose the querySelector
to solve the problem.
在这个例子中,作者选择了querySelector
解决问题。
The getElementsByTagName also returns a live nodeList, and when we append the links to the in-memory unordered list, the link is removed from the document, and the length of the collection is affected.
getElementsByTagName 还返回一个活动的 nodeList,当我们将链接附加到内存中的无序列表时,链接将从文档中删除,并且集合的长度会受到影响。
So
所以
if(you don't want to change the NodeList during the follow-up script work){
"use querySelectorAll"}
else if(you want to change the NodeList during the follow-up script work) {
"use getElementsByTagName"
}
And you can have a try to use getElementsByTagName
in this example,you will see it can't work.
你可以getElementsByTagName
在这个例子中尝试使用,你会发现它不能工作。
回答by Allen Stewart
In this example:
在这个例子中:
<html>
<head>
<meta charset="utf-8">
<title>Yandex</title>
</head>
<body>
<a href="((http://yandex.ru))">Яндекс</a>,
<a href="((http://yandex.com))">Yandex</a>
</body>
<script>
var elems1 = document.getElementsByTagName('a'), // return 2 lements, elems1.length = 2
elems2 = document.querySelectorAll("a"); // return 2 elements, elems2.length = 2
document.body.appendChild(document.createElement("a"));
console.log(elems1.length, elems2.length); // now elems1.length = 3!
// while elems2.length = 2
</script>
</html>
the element that is created is placed after the script tag, and cannot be read by querySelector
. Only the getElementsByTagName
can find the new element.
创建的元素放在 script 标签之后,不能被querySelector
. 只有getElementsByTagName
可以找到新元素。