1

Apparently these two functions are similar, which is more performative? Which one should I use? What's the difference between the two?

document.querySelectorAll()

function funDOM() {
    var x = document.querySelectorAll(".example");
    var i;
    for (i = 0; i < x.length; i++) {
        x[i].style.backgroundColor = "red";
    }
}
<html>
<body onload="funDOM()">
    <div>
        Doubts <span class="example">red</span>
    
    </div>
    <p class="example">red</p>
    
    
</body>
</html>

document.getElementsByClassName()

function funDOM() {
    var x = document.getElementsByClassName("example");
    var i;
    for (i = 0; i < x.length; i++) {
        x[i].style.backgroundColor = "red";
    }
}
<html>
<body onload="funDOM()">
    <div>
        Doubts <span class="example">red</span>
    
    </div>
    <p class="example">red</p>
    
    
</body>
</html>
Harsh Patel
  • 6,334
  • 10
  • 40
  • 73
alxwca
  • 111
  • 2
  • 6
  • 1
    Does https://stackoverflow.com/questions/14377590/queryselector-and-queryselectorall-vs-getelementsbyclassname-and-getelementbyid answer your question? – Cleared Jan 22 '18 at 12:10
  • 6
    `getElementsByClassName` returns a live nodelist, `querySelectorAll` doesn't. – Andy Jan 22 '18 at 12:13

1 Answers1

2

The difference is that querySelectorAll allows you to search for more than just classes. You can search with any CSS selector.

Realistically, there isn't much of a performance difference between the two, but if you only want to search by class name, you should use getElementsByClassName.

EKW
  • 2,059
  • 14
  • 24