Hi. I'm trying to add event listeners to multiple elements of the same class. The DOM is something like this:
<body>
....
.......
..........
<ul class="x">
<li class="a">
....
...
<span class="someclass">
[
<a href="http://someurl/x1>link text</a>
]
</span>
</li>
<li class="b>
....
.....
<span class="someclass>
[
<a href="http://someurl/x1>link text</a>
]
</span>
</li>
<ul class="y">
<li class="a">
....
...
<span class="someclass">
[
<a href="http://someurl/x1>link text</a>
]
....
<ul class="z">
<li class="a">
....
...
<span class="someclass">
[
<a href="http://someurl/x1>link text</a>
]
....
I want to attach an event listener to each of the <a> element inside <span> elements of class "someclass".
Here's what I did
for(var i in document.getElementsByClassName('someclass'))
{
document.getElementsByClassName('someclass')[i].childNodes[1].addEventListener('click', function(){return alert("link clicked");},false);
}
When I run this (in Firebug) I get this error:
TypeError: document.getElementsByClassName('someclass').childNodes is undefined
Even though document.getElementsByClassName('someclass')[S].hasChildNodes(); evaluates to true. (S is any integer literal: 0,1,2...upto to the length of the array-1)
>>>document.getElementsByClassName('someclass')[2].hasChildNodes();
>>>true
Not sure what I'm doing wrong; are there any alternate ways to do this? Thanks.