Forum Moderators: open

Message Too Old, No Replies

Referencing Elements

         

mattr555

9:01 am on Feb 23, 2005 (gmt 0)

10+ Year Member



I know i can use getElementByID and getElementsByTagName but is it possible to get elements by class name?

if getElementsByTagName('Div').length allows me to see how many divs are on the page, how could i get the number of divs with a specified class against them?

Bernard Marx

8:29 pm on Feb 23, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



var output = [];
var divs = document.getElementsByTagName("div");
for(var k=0;k<divs.length;k++)
if(divs[k].className == 'myclass')
output[output.length] = divs[k];

If the divs might have multiple classNames, use a regular expression.
Replace the condition with this one:

if(/\bmyclass\b/.test(divs[k].className))

mattr555

8:41 am on Feb 24, 2005 (gmt 0)

10+ Year Member



Thanks, I understand the first bit but regular expressions are over my head at the minute. any good tutorials for these?

Bernard Marx

3:44 pm on Feb 24, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Just search: "Javascript regular expressions" for a tutorial.
But you don't need to understand them to use the above.
Just replace 'myclass' with the className you are looking for