Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

How to get elements by class

case sensitive element

  • Please log in to reply
3 replies to this topic

#1 Csabi

Csabi

    CC Resident

  • Advanced Member
  • PipPipPipPip
  • 60 posts

Posted 19 August 2010 - 06:29 AM

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 :)
  • 0
If you enjoy reading this discussion and are thinking about commenting, why not click here to register and start participating in under a minute?

#2 gokuajmes

gokuajmes

    CC Devotee

  • Senior Member
  • PipPipPipPipPipPip
  • 483 posts

Posted 27 August 2010 - 03:02 AM

Aah wonderful , but sure what is the profile time to get a element using class name ?
  • 0

#3 wim DC

wim DC

    Roar

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 2681 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Python

Posted 27 August 2010 - 03:40 AM

Why would you write your own getElementByClass if there is a getElementByClassName( ) allready?
document.getElementsByClassName('name');
  • 0

#4 Csabi

Csabi

    CC Resident

  • Advanced Member
  • PipPipPipPip
  • 60 posts

Posted 27 August 2010 - 08:47 AM

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 :)
  • 0
If you enjoy reading this discussion and are thinking about commenting, why not click here to register and start participating in under a minute?





Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download