I am trying to get some elems with the classname “special”.
I found the following script online, but it only returns an empty array.
Does anyone see what’s 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')
wrap contains 22 children, the last one is <p class="special">Lorem</p>, and in firebug I get all the way down to finding the node with the classname, but then it jumps the a.push. Im lost!
edit:
okay so it does work now, it would still be interesting though to know why console.log(a) return an empty array
\bin a string literal is a backspace character. They meant:However this is still wrong, because:
it won’t work for any classnames that contain non-ASCII or non-alphanumeric characters, as that would put the word boundaries in the wrong place;
classnames may contain characters that have special meaning in regex, such as
.; these would need to be escaped.You can find an alternative implementation that should match the standard
document.getElementsByClassNameinterface better in this question.