How to get all elements by class name?
JavascriptJavascript Problem Overview
How do you get all elements by class name using pure JavaScript? Analogous to $('.class')
in JQuery
?
Javascript Solutions
Solution 1 - Javascript
document.getElementsByClassName(klass)
Be aware that some engines (particularly the older browsers) don't have it. You might consider using a shim, if that's the case. It will be slow, and iterate over the whole document, but it will work.
EDIT several years later: You can get the same result using document.querySelectorAll('.klass')
, which doesn't seem like much, but the latter allows queries on any CSS selector, which makes it much more flexible, in case "get all elements by class name" is just a step in what you are really trying to do, and is the vanilla JS answer to jQuery's $('.class')
.
Solution 2 - Javascript
A Simple and an easy way
var cusid_ele = document.getElementsByClassName('custid');
for (var i = 0; i < cusid_ele.length; ++i) {
var item = cusid_ele[i];
item.innerHTML = 'this is value';
}
Solution 3 - Javascript
document.getElementsByClassName('your class');
or you can build your classname like this, if that doesn't work try this
if (!document.getElementsByClassName) {
document.getElementsByClassName=function(cn) {
var allT=document.getElementsByTagName('*'), allCN=[], i=0, a;
while(a=allT[i++]) {
a.className==cn ? allCN[allCN.length]=a : null;
}
return allCN
}
}
Solution 4 - Javascript
In some browsers there is a document.getElementsByClassName(class)
function. Otherwise, the only option you have is to iterate over all elements in the document by checking each of it against your condition of having the required class name.
Solution 5 - Javascript
Several techniques described and speed tested here: http://ejohn.org/blog/getelementsbyclassname-speed-comparison/
Solution 6 - Javascript
This should work:
function(className)
{
var matchingItems = [];
var allElements = document.getElementsByTagName("*");
for(var i=0; i < allElements.length; i++)
{
if(allElements [i].className == className)
{
matchingItems.push(allElements[i]);
}
}
return matchingItems;
}
Solution 7 - Javascript
function getElementsByClassName(oElm, strTagName, strClassName){
var arrElements = (strTagName == "*" && oElm.all)? oElm.all :
oElm.getElementsByTagName(strTagName);
var arrReturnElements = new Array();
strClassName = strClassName.replace(/-/g, "\-");
var oRegExp = new RegExp("(^|\s)" + strClassName + "(\s|$)");
var oElement;
for(var i=0; i<arrElements.length; i++){
oElement = arrElements[i];
if(oRegExp.test(oElement.className)){
arrReturnElements.push(oElement);
}
}
return (arrReturnElements)
}