I am attempting to retrieve elements with the class name "special". I came across this code snippet online, but unfortunately, it only gives back an empty array.
Can anyone spot what may be going wrong?
getElementsByClassName = function (node, classname){
var a = [],
re = new RegExp('\b' + classname + '\b'),
els = node.getElementsByTagName("*"),
l = els.length,
i;
for (i = 0; i < l; i += 1) {
if (re.test(els[i].className)) {
a.push(els[i]);
}
}
console.log(a)
return a;
}
var wrap = document.getElementById('wrap');
getElementsByClassName(wrap, 'special')
The wrap element has 22 children, with the last one being
<p class="special">Lorem</p>
. In Firebug, I can locate the node with the correct class name, but for some reason, it skips the a.push. I'm at a loss here!
edit: After some further debugging, it seems that the code is working now; however, it would still be helpful to understand why console.log(a) was initially returning an empty array