Jump to content

How to get elements by class

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
3 replies to this topic

#1
Csabi

Csabi

    Learning Programmer

  • Members
  • PipPipPip
  • 62 posts
I will show you two ways to get an element by class: using getElementsByTagName or creating a getElementByClass function:

1. Using getElementsByTagName
This code loops through each element of the page and check`s it`s class name:
for(var i=0;i<document.getElementsByTagName('*').length;i++){

   if(document.getElementsByTagName('*')[i].className == 'YOUR-CLASS'){

      document.getElementsByTagName('*')[i].style.backgroundColor = 'black';

   }

}
2. Creating a getElementsByClass function
This code creates the getElementsByClass function what returns an array of elements with the selected class name:
document.getElementsByClass = function(class){

   var itemsfound = new Array;

   var elements = document.getElementsByTagName('*');

   for(var i=0;i<elements.length;i++){

      if(elements[i].className == class){

         itemsfound.push(elements[i]);

      }

   }

   return itemsfound;

}
Use it in the following way to select only the element with the specified index:
document.getElementsByClass('YOUR-CLASS')[0].style.backgroundColor = 'black';
Or use this if you want to select each element:
for(var i=0;i<=document.getElementsByClass.length;i++){

   document.getElementsByClass('YOUR-CLASS')[i].style.backgroundColor = 'black';

}
Note: Javascript is case sensitive
If you like it don`t forget the +rep :)

#2
gokuajmes

gokuajmes

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 518 posts
Aah wonderful , but sure what is the profile time to get a element using class name ?

#3
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
Why would you write your own getElementByClass if there is a getElementByClassName( ) allready?
document.getElementsByClassName('name');

#4
Csabi

Csabi

    Learning Programmer

  • Members
  • PipPipPip
  • 62 posts
Hm..... you are right :)
I`m using adobe dreamweaver and when I`m typing a function it shows a list of valid DOM functions and there was no ClassName, but now I`we searched and you are right, it exists :)