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?
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?
Share Improve this question asked Apr 2, 2014 at 0:28 Emerson BarcellosEmerson Barcellos 1613 silver badges6 bronze badges1 Answer
Reset to default 8You 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";
});