You can use a selector library, for example Sizzle: http://sizzlejs.com/ , but if you want pure JS, I think you're stuck with getting all the elements, and then programmatically โpick upโ those that have classes that Are you interested in using RegEx, for example:
This is the equivalent of your jQuery oneliner:
for( i in document.all) document.all[i].className && /\bpost-text\b/g.test(document.all[i].className) && (document.all[i].style.color = "red")
:)
If you don't need it on one line, you can do it faster ( and much more readable ):
var myClassName = "someClass"; var regexp = RegExp("\\b"+myClassName+"\\b/g"); var elements = document.all; for( i in elements){ var this_element = elements[i]; if(regexp.test(this_element.className){ this_element.style.color = "red"; } }
If " for (i in the object) " does not work for you, just use the classic for the loop " for (var i = 0; i <elements.length; i ++) ".
It can be โdecoratedโ a bit using slightly more advanced JS concepts (array function comparisons, folding, etc.), in which version of JS are you encoding again? I think this is not ECMA Script 5, right?
Also check this question / answer Get all elements in an HTML document with a specific CSS class
nana
source share