http://jsfiddle.net/walkerneo/QqkkA/
I've seen many questions here either asking about or being answered with event delegation in javascript, but I've yet to see, however, how to use event delegation for elements that aren't going to be the targets of the click event.
For example:
HTML:
<ul>
<li><div class="d"></div></li>
<li><div class="d"></div></li>
<li><div class="d"></div></li>
<li><div class="d"></div></li>
<li><div class="d"></div></li>
<li><div class="d"></div></li>
</ul>
CSS:
ul{
padding:20px;
}
li{
margin-left:30px;
margin-bottom:10px;
border:1px solid black;
}
.d{
padding:10px;
background:gray;
}
What if I want to add a click event to handle the li
elements when they're clicked? If I attach an event handler to the ul
element, the div
s will always be the target elements. Apart from checking every parent of the target element in a click function, how can I accomplish this?
edit:
I want to use event delegation instead of:
var lis = document.getElementsByTagName('li');
for(var i=0;i<lis.length;i++){
lis[i].onclick = function(){};
}
But if I do:
document.getElementsByTagName('ul')[0].addEventListener('click',function(e){
// e.target is going to be the div, not the li
if(e.target.tagName=='LI'){
}
},false);
EDIT: I'm not interested in how to use Javascript libraries for this, I'm interested in how they do it and how it can be done with pure js.
Here's one way to solve it:
var list = document.getElementsByTagName('ul')[0]
list.addEventListener('click', function(e){
var el = e.target
// walk up the tree until we find a LI item
while (el && el.tagName !== 'LI') {
el = el.parentNode
}
console.log('item clicked', el)
}, false)
This is overly simplified, the loop will continue up the tree even past the UL element. See the implementation in rye/events for a more complete example.
The Element.matches
, Node.contains
and Node.compareDocumentPosition
methods can help you implement this type of features.
There is now a method on elements called closest
, which does exactly this. It takes a CSS selector as parameter and finds the closest matching ancestor, which can be the element itself. All current versions of desktop browsers support it, but in general it is not ready for production use. The MDN page linked above contains a polyfill.
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