What is the difference between querySelectorAll () and getElementsByClassName ()

0

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>
        Duvidas <span class="example">vermelhas</span>
    
    </div>
    <p class="example">vermelho</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>
        Duvidas <span class="example">vermelhas</span>
    
    </div>
    <p class="example">vermelho</p>
    
    
</body>
</html>

Thank you in advance for your consideration.

    
asked by anonymous 22.01.2018 / 13:02

1 answer

1

getElementsByClassName returns DOM elements live and any subsequent changes made to those DOM elements will be reflected in the list.

querySelectorAll does not return live DOM elements. Subsequent changes in the document structure will not be reflected in the returned NodeList object. The element basically contains a list of nodes present in the document at the time it was created.

Suppose you have a class called bg-blue and this class is used in 5 different elements. When doing

var myElem = documento.getElementsByClassName("bg-blue");

The variable myElem would have the 5 elements that contain the class. To access a specific element you could do as follows.

var myElem = documento.getElementsByClassName("bg-blue")[0];

In this way it will return the first element of the DOM with the class bg-blue

    
22.01.2018 / 13:35