http://jsfiddle.net/walkerneo/QqkkA/
In the realm of Javascript event delegation, there are many discussions related to using it for elements that serve as targets for click events. However, a less explored topic is how to implement event delegation for elements that are not necessarily the targets of the click event.
Take, 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;
}
How can we add a click event handler for the li
elements when they're clicked? Attaching an event handler directly to the ul
element will always result in the div
s being the target elements. Besides checking every parent of the target element within a click function, is there another way to achieve this?
Edit:
I am looking to utilize event delegation instead of:
var lis = document.getElementsByTagName('li');
for(var i=0;i<lis.length;i++){
lis[i].onclick = function(){};
}
However, if I attempt:
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 utilizing Javascript libraries for this. My focus is on understanding how it's done and implementing it with pure js.