Reputation: 5174
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
Reputation: 708016
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.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
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
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
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