Adib Aroui
Adib Aroui

Reputation: 5067

document.getElementsByClassName("sth") vs document.querySelectorAll("#id tagname")

Given the following HTML:

   <ul id="menu-mobile" >
            <li class="menu"><a href="#">Link 1</a></li>
            <li class="menu"><a href="#">Link 2</a></li>
            <li class="menu"><a href="#">Link 3</a></li>
   </ul>

How to target all the <li>s in the best approach? is it by using the class name or by the id with querySelectorAll()?

var menuLink = document.querySelectorAll( '#menu-mobile li' );    
for (var i = 0; i < menuLink.children.length; i++) {
var childElement = menuLink.children[i];
childElement.addEventListener('click', doSomething, false);
}

function doSomething() {
    alert("Hello");
}

and

var menuLink = document.getElementsByClassName( 'menu' );    
for (var i = 0; i < menuLink.children.length; i++) {
var childElement = menuLink.children[i];
childElement.addEventListener('click', doSomething, false);
}

function doSomething() {
    alert("Hello");
}

both work.

Thanks

Upvotes: 2

Views: 141

Answers (2)

CrazyCrow
CrazyCrow

Reputation: 4235

It depends. getElementsByClassName is much faster and this fact could be useful if you need max performance. querySelectorAll is more developer-friendly in case of complex queries to DOM.

Upvotes: 1

Quentin
Quentin

Reputation: 943108

querySelectorAll doesn't require that you block your markup by adding a class to every element in the list (and is supported by IE8).

Upvotes: 3

Related Questions