3 Replies - 594 Views - Last Post: 13 June 2008 - 11:43 AM

#1 atdrago  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 27
  • Joined: 08-June 08

Getting an Element by Class

Post icon  Posted 13 June 2008 - 09:22 AM

Hello, all.

Is there any way to get an element by class, instead of id?

I'd like to select every paragraph element of a certain class in my HTML, and do some stuff to that paragraph. There will be several paragraphs of this class (hence using class) so adding the id attribute isn't really an option (I think).

Any suggestions?

Thanks!
Is This A Good Question/Topic? 0
  • +

Replies To: Getting an Element by Class

#2 level1  Icon User is offline

  • D.I.C Head

Reputation: 14
  • View blog
  • Posts: 65
  • Joined: 12-June 08

Re: Getting an Element by Class

Posted 13 June 2008 - 09:43 AM

There sure is a way. All the prebuilt libraries like jquery, prototype have it. My suggestion is google prototype - or better for you prototype.lite.js download it, link to it then you can use the command

document.getElementsByClassName('className')

I'd like to point out that this script can be slow especially for large documents. I modifed the prototype function and add a container to it for personal use, so that it only looks within my container and not the entire document. For me it knocked off like 3s script time. So, beware of overusing it, but for basic page it kicks ass!!!
Was This Post Helpful? 0
  • +
  • -

#3 quim  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 18
  • View blog
  • Posts: 182
  • Joined: 11-December 05

Re: Getting an Element by Class

Posted 13 June 2008 - 11:23 AM

This function does it for you, if you don't want to use any library:
function getElementsByClassNameEx( htmlObj, theClassName )
{
		var theObj = document.getElementsByTagName( htmlObj );
		
		for( var i = 0; i < theObj.length; i++ )
		{
				if( theObj[ i ].className == theClassName )
				{
						/* manipulate the objects 
						with the chosen class name */				
				}
		}
}

I just didn't name the function to getElementsByClassName to avoid any confusion with the DOM implementation comming up in HTML 5, as seen in link below.
http://www.w3.org/TR...entsbyclassname
Was This Post Helpful? 1
  • +
  • -

#4 atdrago  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 27
  • Joined: 08-June 08

Re: Getting an Element by Class

Posted 13 June 2008 - 11:43 AM

Thanks, quim! Who knew there was a className method.

Thanks also level1, but I try to stay away from big libraries like jquery and such primarily because I like to write the code myself, and like you said, they're huge.

Thanks again guys.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1