Forum Moderators: open

Message Too Old, No Replies

Run Function On getElementsByTagName onclick

         

itledi

11:36 pm on Jan 3, 2008 (gmt 0)

10+ Year Member



I'm trying to have a function run when a tag name is clicked.

I have the following script in my head, but to no success.

<script type="text/javascript">
document.getElementsByTagName("td").onclick=function(){alert("click");}
</script>

enoj

11:57 pm on Jan 3, 2008 (gmt 0)

10+ Year Member



document.getElementsByTagName("td") returns a nodelist, not a single element. That means you are setting the onclick property on the wrong element (the nodelist instead of the actual elements).

If there always is only one element returned, you can use document.getElementsByTagName("td")[0].onclick, but you would probably want to loop over the elements, like this:


tds = document.getElementsByTagName("td");
for( var x=0; x < tds.length; x++ ) {
tds[x].onclick = function(){
alert('Click!');
};
}

itledi

12:04 am on Jan 4, 2008 (gmt 0)

10+ Year Member



Thank you, that makes sense.

For testing, I changed the script from td to h3, as there is only one of those and set the script to:

<script type="text/javascript">
document.getElementsByTagName("h3")[0].onclick=function(){alert("click");}
</script>

Unfortunatly, this doesn't seem to work either.

Do I need to "turn on" this thing or will JavaScript always be watching out for the onclicks, or do I need to put it in something like onload?

Thanks

daveVk

3:36 am on Jan 4, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



or do I need to put it in something like onload

Yes you need to wait for document to load first.