user3086509
user3086509

Reputation: 135

EventListener performance ByID vs. ByTagName

Lets say my DOM looks like this

<nav id="nav">
    <a>link</a>
    <a>link</a>
    <a>link</a>
</nav>

to check for clicks on the links inside Javascript i could write

var nav = document.getElementByID("nav")
nav.addEventListener("click", function(event){})

or also

var links = document.getElementsByTagName("a");
links.addEventListener("click", function (e){});

now i wonder, since the second method (ElementsByTagName) returns an array of the elements, does that also mean that this will init multiple (in this case 3) EventListeners? Because a greenhorn like me would then say that the first method is much more performant?!

Upvotes: 0

Views: 64

Answers (1)

Noah Freitas
Noah Freitas

Reputation: 17430

Because click events bubble, you can add a single click event listener to the <nav> element and receive all clicks to it and its child <a> elements. This is known as event delegation and is more performant than adding a different listener to each <a>.

document.querySelector('nav').addEventListener('click', function (e) {
    if (e.target.nodeName.toLowerCase() === 'a') {
        // One of the nav's child a elements was clicked.
        // Now you can do something with it:
        e.target.classList.add('clicked');
    }
});

Upvotes: 1

Related Questions