If I have 10 items, with the class name keyword:
<div class="keyword"></div>
How can I attach an event, for example click, on this element.
I tried the following, but with no luck: (no alert comes up)
document.getElementsByClassName('.keyword').onclick = function()
{
alert(true);
Search.addKey(this.getElementsByClassName('name')[0].innerHTML);
}
Requirements:
- Without the onclick attribute
- no jQuery or any other library
Note: the elements are not generated on page load. Their number can be different, each times you click a button for eg.
I need a way to attach to all tags with the class ‘keyword’ in the ‘future’.
You should delegate the event. Try this:
You can read more on event delegation on quirksmode.com. AFAIK, this is the best way of achieving what you’re trying to achieve. This is how all the major libs (prototype, jQuery, …) work behind the scenes
Update:
Here’s the fiddle, it contains some more explanation. An interesting reference is this page. It helped me understand the way IE and W3C events differ and, crucialy, it helped me understand the value, and countless benefits of Event Delegation