Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
436 views
in Technique[技术] by (71.8m points)

javascript - What is the difference between querySelectorAll and getElementsByTagName?

I was wondering about two different syntax of selecting element in JavaScript.

suppose if I want to select all divs from current document then:

var divs = document.getElementsByTagName("div");
console.log("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");
console.log("There are "+divs.length+" Divs in Document !");

When both of them works in the same way. What's the difference between them ?

Which one is faster? Why? How both works?

Thanks in advance. I've seen the questions like this but they didn't satisfied the need.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Most answeres are wrong. Nicolae Olariu is the only, who answered correcly

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...