boolean12
boolean12

Reputation: 110

Adding event listeners to multiple elements with JavaScript

What I am trying to do is target all the a tags within #menu-wrap li's. I'm fairly new to JS so I'm sorry if I'm missing something obvious!

JavaScript:

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

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

HTML

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

Upvotes: 1

Views: 1898

Answers (2)

Rando Hinn
Rando Hinn

Reputation: 1322

Document.querySelector gets the first element only. But you can do this with classes. Do this. Just attatch class sth to anything you want to have the function.

HTML

<div class="menu-wrap" id="menu-wrap">
            <nav class="menu">
                <ul id="menu-mobile-menu" class="menu">
                    <li class="sth"><a href="#">Link 1</a></li>
                    <li class="sth"><a href="#">Link 2</a></li>
                    <li class="sth"><a href="#">Link 1</a></li>
                </ul>
            </nav>
</div>

JS

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

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

Upvotes: -1

Quentin
Quentin

Reputation: 943571

querySelector:

Returns the first element within the document (using depth-first pre-order traversal of the document's nodes|by first element in document markup and iterating through sequential nodes by order of amount of child nodes) that matches the specified group of selectors.

You want to use querySelectorAll and then loop over the resulting node list (or you want to bind your event handler to #menu-wrap itself and then use event.target to determine which list item was clicked on).

List items are not designed to be interactive controls. You should use a link or button instead.

Upvotes: 3

Related Questions