Pew Pew Laser Blog

Code. Glass art. Games. Baking. Cats. From Seattle, Washington and various sundry satellite locations.

Pew Pew Laser Blog Archives — by Blog ID

getElementsByClass.

6.6.2011

You know about getElementById(), and getElementsByTagName(), but what about getting elements by class?

Yes, there is a native JavaScript function getElementsByClassName(). It is supported by FF3+, Safari 4+, Chrome 4+, Opera 10+, but not IE6, IE7, or IE8.

Here's a simple way to take action on all elements with a given class:

var theScript = document.createElement('script');
<h2 class="myAwesomeClass">My Awesome Header</h2>
<p>This is a paragraph.</p>

<script type="text/javascript">
elems = document.getElementsByTagName("h2");
for ( i=0; i<elems.length; i++ )
{
if ( elems[i].className == "myAwesomeClass" )
   { elems[i].style.color = "red"; }
}
</script>

For the HTML shown, the JavaScript creates an array of all elements with a given tag name. A for loop checks the class of each element in the array, and performs some action on that element if its class matches. (If your class occurs on multiple types of elements, just specify "*" for the class name. )

This is a pretty good solution for just a few lines of code. For lots more flexibility with just a few lines of code more, Dustin Diaz has written his own getElementsByClass function.

Permalink

Tags: code javascript

Authorized users may log-in to leave a comment.

Last Blog: Oh! Chocolate.

Next Blog: Remember When?