Pritesh Mahajan
Pritesh Mahajan

Reputation: 5174

How to get class name through JavaScript

How do I get the class name through JavaScript given no id with this span.

Like: <span class="xyz"></span>

I want to change the background color of this span.

How can I solve this? Please help me.

tympanus.net/Tutorials/CSS3PageTransitions/index3.html#contact

Upvotes: 8

Views: 102515

Answers (4)

jfriend00
jfriend00

Reputation: 708016

You have the following choices:

  1. Use document.getElementsByClassName("xyz"). This will return a NodeList (like an array) of objects that have that class name. Unfortunately, this function does not exist in older versions of IE.
  2. Use document.getElementsByTagName("span") and then loop over those objects, testing the .className property to see which ones have the desired class.
  3. Use document.querySelectorAll(".xyz") to fetch the desired objects with that class name. Unfortunately this function does not exist in older browsers.
  4. Get a library that automatically handles all CSS3 selector queries in all browsers. If you want just a selector library, then you can use Sizzle. If you want a more comprehensive library for manipulating the DOM, then use YUI3 or jQuery (both of which have Sizzle built-in).

As of 2011, my advice is option #4. Unless this is a very small project, your development productivity will improve immensely by using a CSS3 selector library that has already been developed for cross-browser use. For example in Sizzle, you can get an array of objects with your class name with this line of code:

var list = Sizzle(".xyz");

In jQuery, you can create a jQuery object that contains a list of objects with that class with this line of code:

var list = $(".xyz");

And, both of these will work in all browsers since IE6 without you having to worry about any browser compatibility.


In more modern times (like 2021), you can use built in document.querySelectorAll() and see fairly rich CSS3 selector support.

Upvotes: 6

Avinash Raut
Avinash Raut

Reputation: 2113

You can use a jquery to solve the same issue.

 var classname = $(this).attr('class'); //here you will get current class name if its with multiple class split it and take first class.
   $("."+classname.split(" ")[0]).css("background-color", "yellow");

Upvotes: 3

endyourif
endyourif

Reputation: 2202

Something like this should work:

var spans = document.getElementsByTagName("span");
for (var i = 0; i < spans.length; i++) {
    if (spans[i].className == 'xyz') {
        spans[i].style.backgroundColor = '#000';
    }
}

Upvotes: 12

Gabi Purcaru
Gabi Purcaru

Reputation: 31564

You can use document.getElementsByClassName('xyz'). Note: it returns an array a NodeList (thanks to @IAbstractDownvoteFactory) since there can be multiple elements with the same class.

var spans = document.getElementByClassName('xyz');
var i;
for(i=0; i<spans.length; i++) {
    spans[i].style.backgroundColor = your_color;
}

Upvotes: 4

Related Questions