What is the difference between querySelectorAll and getElementsByTagName?

Selections

getElementsByTagName only selects elements based on their tag name. querySelectorAll can use any selector which gives it much more flexibility and power.

Return value

  • gEBTN returns a live node list.
  • qSA returns a static node list.

Live node lists can be useful (you can query once, store the value, and have it update as the DOM changes) but are responsible for a lot of confusion such as the example in this question.

Usually a static list is easier to deal with.

Support

See caniuse for gEBTN and qSA.

gEBTN has more support, but qSA has support in all browsers that are relevant for most use cases today.

Performance

You probably shouldn't care. These functions are unlikely to be a bottleneck in your code.

I've seen conflicting reports about which is faster. It likely varies between browsers anyway.


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.

Tags:

Javascript