What\'s the best way to get an array of all elements in an html document with a specific CSS class using javascript?
No javascript frameworks like jQuery allowed her
1) Get all elements in the document (document.getElementsByTagName('*'))
2) Do a regular expression match on the element's className attribute for each element
There is no such thing as a CSS class. CSS has rule-sets and selectors (including the class selector).
Do you mean an HTML class? The usual way is to loop over every element in the document (using document.getElementsByTagName('*')
(for efficiency, use a specific tag name if you know the class will only be applied to elements of a certain type) and test the className
property of each (noting that the property contains a space separated list of class names, not a single class name).
A number of libraries (such as jQuery or YUI) have functions to simply this.
Do you mean a CSS selector? This gets more complex, and turning to a library is almost certainly the right thing to do here. Again, jQuery or YUI are decent choices.
If using a framework, they all have selections using CSS Selectors. Otherwise.
var getElementsByClassName = function(cls, sc){
//Init
var elements, i, results = [], curClass;
//Default scope is document
sc = sc || document;
//Get all children of the scope node
elements = sc.getElementsByTagName('*');
for( i=0; i < elements.length; i++ ){
curClass = elements[i].getAttribute('class');
if(curClass != null){
curClass = curClass.split(" ");
for( j=0; j < curClass.length; j++){
if(curClass[j] === cls){
results.push( elements[i] );
break;
}
}
}
}
return results;
};
Just wrote it right now, just for you. :) Feel free to use.
You can include a getElementsByClass function, or you can use a jQuery selector.
UPDATE: The implementation mentioned by @Shog9 is probably better than that above.