Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if an element of a list was clicked in javascript?

how do I know if an element of a list was clicked in javascript?

<div id="list">
<a href="#">one</a>
<a href="#">two</a>
<a href="#">three</a>
</div>

with Jquery is:

$('#list a')

JavaScript and how do I do?

like image 434
Emerson Barcellos Avatar asked Feb 14 '23 08:02

Emerson Barcellos


1 Answers

You can use delegated event handling that takes advantage of event propagation so you put one event handler on the parent and it sees all the events from the children:

document.getElementById("list").addEventListener("click", function(e) {
    // e.target will be the item that was clicked on
    e.target.style.color = "#F00";
})

Or, you could attach an event handler to each link directly by enumerating the links that are children of the list:

var links = querySelectorAll("#list a");
for (var i = 0; i < links.length; i++) {
    links[i].addEventListener("click", function(e) {
    this.style.color = "#F00";
})

FYI, if programming in plain javascript, I find it very useful to use a few utility functions that help you iterate lists of HTML objects which are often returned from DOM functions:

// do a querySelectorAll() and then call a function on each item
// the parent argument is optional (defaults to document)
function iterateQuerySelectorAll(selector, fn, parent) {
    parent = parent || document;
    var items = parent.querySelectorAll(selector);
    for (var i = 0; i < items.length; i++) {
        fn(items[i]);
    }
}

// add an event handler to each item that matches a selector
// the parent argument is optional (defaults to document)
function addEventQuerySelectorAll(selector, event, fn, parent) {
    iterateQuerySelectorAll(selector, function(item) {
        item.addEventListener(event, fn);
    }, parent);
}

Then, with these utility helpers, the second example of code above would simply be this:

addEventQuerySelectorAll("#list a", "click", function() {
    this.style.color = "#F00";
});
like image 74
jfriend00 Avatar answered Feb 16 '23 02:02

jfriend00