Reputation: 445
Learning DOM0 javascript and the prof has thrown a curveball. He writes dozens of paragraphs with class names: sports, life, books, comedy and then this:
<p class="sports books comedy">
I found this book: http://www.amazon.com/Teed-Off-Laughs-Greens-Sports/dp/0233995005/ref=sr_1_1?ie=UTF8&s=books&qid=1277749796&sr=1-1 You don't have to be good to play, but a low level of self-esteem is helpful! Humorous collection of colour photographs and hilarious text reduces our heroes of the golf course to mere mortals. No golfing disaster is left secret and the 80 photographs only go to prove the fallibility of international stars.
</p>
Have to style it without using Jquery, my thought was this:
window.onload=function(){
var elements = document.getElementsByTagName('*');
for (var i=0; i<elements.length; i++) {
if (elements[i].className == 'sports') {
elements[i].style.border="2px solid green";
}
else if (elements[i].className == 'life') {
elements[i].style.color="red";
}
else if (elements[i].className=="books") {
elements[i].style.textAlign="right";
}
else if (elements[i].className=="comedy") {
elements[i].style.fontSize="200%";
}
}
}
Which works for everything except the multiple classname. Trying to find a way around it.
Upvotes: 1
Views: 71
Reputation: 21
elements[i].classList.contains('sports')
ben336's answer works too, and used to be the best way to go about it, but now that there's a native way to do it we should prefer that (because it's faster and less code). The only downside is that it won't work in IE8 or IE9 without a polyfill.
Upvotes: 2
Reputation: 25728
elements[i].className.indexOf('sports') >= 0
will work if any of the classes are sports, though it will also add issues with substrings (will match "othersports" too)
So probably
var classlist;
classlist = elements[i].className.split(/\s+/);
if(classlist.indexOf('sports') >= 0)
Thats a bit more verbose, but should fit what you want to do.
Upvotes: 4