I'm trying to build a script that detects the particular <span>
the user clicks on and outputs the value of the contents of that clicked span.
My HTML looks like this:
<div id="span-container">
<span>Lorem</span>
<span>Ipsum</span>
<span>Something...</span>
<span>Something...</span>
<span>Amet</span>
</div>
And my Javascript looks like this:
div = document.getElementById("span-container");
spans = div.getElementsByTagName("span");
for(var i = 0; i < spans.length; i++) {
spans[i].onclick = function() {
alert(spans[i].innerHTML);
}
}
Attempting to run this code results in a Cannot read property 'innerHTML' of undefined
error.
I'm sure giving each span an ID that correlates to its contents like <span id="lorem">Lorem</span>
would work, but I'm optimistic that a more elegant solution exists.
I'd also like to avoid using jQuery if possible. Thanks!