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?
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";
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With