Skip to main content. Skip to secondary content (sidebar).

Using JavaScript to access an HTML element with multiple class names

Occasionally I discover a nifty solution to a coding obstacle. Although seemingly small, these can be major productivity barriers, especially if you are only a recreational coder. The following is in response to an HTML element that has multiple class names declared.

Our HTML looks something like this:

XHTML:
<div id="myElement" class="first second third">
   My Element
</div>

The element has three class names declared: first, second, and third. Depending on the scenario, you may need to find out if this element has the second class. Typically, you would use the following JavaScript:

JavaScript:
<script language="JavaScript">
window.onload = function()
{
   if (document.getElementById("myElement").className == "second")
   {
      alert("Congratulations, this element has the 'second' class name!");
   }
}
</script>

However, you will discover that even though our element has the second class associated with it, the alert does not fire. That is because the actual class name is not second, but is in fact first second third.

In order to detect whether or not this element has a specific class associated with it, it is better to use the following JavaScript:

JavaScript:
<script language="JavaScript">
window.onload = function()
{
   if (document.getElementById("myElement").className.indexOf("second") != -1)
   {
      alert("Congratulations, this element has the 'second' class name!");
   }
}
</script>

The alert will now fire properly.

The only caveat is to pay special attention to your class names. In the above example, if your element had the class names first_second, third, and fourth, then your alert would still fire. This is because your class name does contain an index of the word “second”, even though it does not contain the second class. Depending on the complexity of your Web site or Web application, an alternative would be to use a regular expression in order to guarantee an accurate match.

In reality, this is most helpful when you need to find out whether or not several different elements have a specific class associated with them. For this robust functionality, I would suggest using a library, such as jQuery.

Tags: ,
Bookmark At Delicious

A day late and a dollar short... comments are closed.

01  |  October 9th, 2007 at 11:22 am

Hi there, 2 things:

1.) Commenter above me is a bunch of link spam (you may want to clear it out)

2.) I would recommend a regex approach, that matches on (pseudo code)…

optionalSpace, className, optionalSpace

With this, you will always get the correct match every time.

e.g.

function hasClassName(el, name){
var re = new RegExp(’(^| )’ + name + ‘( |$)’);
if(re.test(el.className)){
return true;
}
return false;
}

Comment by:

Steve

02  |  October 9th, 2007 at 11:47 am

Hi Steve,

Thanks for that code snippet and for the note about the spam comment. Not sure how that one got through.

Comment by:

Brian

03  |  November 15th, 2007 at 2:57 pm

This is great for finding the class, but how about switching classes on the fly?

<a href=”…” rel=”nofollow”>’07 Model</a>
<a href=”…” rel=”nofollow”>’08 Model</a>

When the user selects the ‘08 model, ideally i would like to remove the class from the first button and add it to the second.

(I am aware of the a:hover, a:active, etc - this is just an example).

Comment by:

Brad

04  |  November 15th, 2007 at 3:06 pm

To answer my own question and furthur extend the functionality here, I found this great set of functions on Google Here

Comment by:

Brad

05  |  July 17th, 2008 at 3:57 pm

Just wanted to drop a thank you for the poster and commenters here. Helped me get this working in IE6/7.

This is a segment of code that I have written to enable tab selecting on a new page we’re building out. It allows you to use a structure for your tabs. CSS styling not included =)

//** Add click selecting to search option tabs **
registerSearchSelect = function(varElement){
var searchObj = document.getElementById(varElement).getElementsByTagName(”li”);
for (var i=0; i<searchObj.length; i++) {
searchObj[i].onclick=function() {
for(var i=0;i<searchObj.length;i++){
var re = new RegExp(’(^| )selected( |$)’);
re.test(searchObj[i].className) ? searchObj[i].className = searchObj[i].className.replace(new RegExp(”selected”), “”) : function(){};
}
this.className+=” selected”
return false;
}
}
}
window.attachEvent ? window.attachEvent(”onload”, function(){ registerSearchSelect(”mastheadSearch”) }) : window.addEventListener(”load”, function(){ registerSearchSelect(”mastheadSearch”) }, false);

Comment by:

Charles Lawrence

06  |  July 22nd, 2008 at 3:14 am

Hi Charles,

Sorry it took me so long to post that… thanks for sending it along for others to review.

Comment by:

Brian