How do I get the class name through JavaScript given no id with this span
.
Like:
I want to
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';
}
}
You have the following choices:
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.document.getElementsByTagName("span")
and then loop over those objects, testing the .className
property to see which ones have the desired class.document.querySelectorAll(".xyz")
to fetch the desired objects with that class name. Unfortunately this function does not exist in older browsers.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.
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;
}
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");