Modifing the CSS Class Assigned to a Tag
16th August 2005 | 0 Comments
In an older version of my blog I posted how to attach new styles to an existing stylesheet. While that method its incredibly useful, its kind of dirty. A better way is to change the class assigned to the HTML tag which is easy if the tag has an id attribute, but what if you don't.
This is where the getElementsByTagName function comes into play. This function returns an array of tags. For example if I typed var s = document.getElementsByTagName("span");, it would return an array of all the span tags on my page.
Now what if I don’t want to change the class associated with each span tag. You can also use the className attribute to do comparison operations. The following example grabs all the span tags on the page and changes only the span tags with the class of spoiler-hide.
var spanTags = document.getElementsByTagName("span");
var c = spanTags.length;
for(var i = 0; i < c; i++) {
if (spanTags[ i ].className == "spoiler-hide") {
spanTags[ i ].className = "spoiler-show";
}
}
Have fun!
Leave a Comment