javascript: getElementsByClass
Im looking to do something simple and the site is not heavy with js so im not using a js framework for this.
I am trying to add event click listener, I am trying to get element by class. I found the following function + others that I have tried but for some reason none of them are finding the elements.
function getElementsByClass( searchClass, domNode, tagName) {
if (domNode == null) domNode = document;
if (tagName == null) tagName = '*';
var el = new Array();
var tags = domNode.getElementsByTagName(tagName);
开发者_如何学运维 var tcl = " "+searchClass+" ";
for(i=0,j=0; i<tags.length; i++) {
var test = " " + tags[i].className + " ";
if (test.indexOf(tcl) != -1)
el[j++] = tags[i];
}
return el;
}
var els = getElementsByClass("wow");
alert(els.length);
i have a couple of divs with the class wow, testing but I keep getting 0.
Assuming your function works properly, do it when the DOM is ready or on window load. Or call it before the end body tag.
DEMO: http://jsfiddle.net/rXApk/
The class attribute takes a space separated list of class names, not a comma separated list.
Your test won't match wow,
as it looks for wow
.
精彩评论