Forum Moderators: open

Message Too Old, No Replies

Using Javascript to find tags of a certain class

How is it done?

         

lobo235

12:13 am on Jul 20, 2005 (gmt 0)

10+ Year Member



I would like to be able to use javascript to scan my entire html document for tags with a certain class, for example, class="blah". I then want to apply an onclick event to each one of those elements with the "blah" class. How can this be done effectively and efficiently?

RonPK

8:44 am on Jul 20, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



That should not be difficult if you know which tags (elements) you're looking for. Example: if you're searching for all <div>s , document.getElementsByTagName('div') will return an array with all divs in the document. Loop through them, and check the className property.

It is more complicated if you do not know which elements you're looking for. You'd have to parse the entire document tree.

lobo235

11:53 am on Jul 20, 2005 (gmt 0)

10+ Year Member



Thank you for your help, I should be able to figure this out now.

lobo235

2:06 pm on Jul 20, 2005 (gmt 0)

10+ Year Member



Okay, I have created the following function that I am trying to use. The function should find all the <label> elements in the document and check the class of each object to see if it is of the class "checks". If the className is "checks" then it's supposed to add an onclick even to each of these labels.

function labelOnclick( ) 
{
labels = document.getElementsByTagName("label");
for( var i = 0; i < labels.length; i++ )
{
if( labels[i].className == 'checks' )
labels[i].onclick = toggleColor( labels[i].id );
}
}

Well, it's not working. My toggleColor function is being called for each label when the document loads and the onclick does not work for any of the labels.

Any ideas?

RonPK

4:54 pm on Jul 20, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



It may work if you don't pass any parameters to the event handler. So replace

labels[i].onclick = toggleColor( labels[i].id );

with

labels[i].onclick = toggleColor;

In toggleColor you can get the ID by reading this.id, e.g.

document.getElementById(this.id).style.color = 'red';

lobo235

7:04 pm on Jul 20, 2005 (gmt 0)

10+ Year Member



This worked perfectly. Thank you very much for your help. Just curious, why does having the parameters make any difference?

RonPK

8:10 pm on Jul 20, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Good question ;) I'm sure there is a reason, but I really don't know the answer. All I know is that the object that triggers the event, in this case one of the labels with classname 'checks', automatically becomes part of the local scope of the method that handles the event. The same goes for all the object's properties. So there is no need to 'inject' them into the method.