Forum Moderators: open
function getElementsByClass(searchClass, node, tag) {
var classElements = new Array();
if ( node == null )
node = document;
if ( tag == null )
tag = '*';
var els = node.getElementsByTagName(tag);
var elsLen = els.length;
var pattern = new RegExp("(^¦\s)"+searchClass+"(\s¦$)");
for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
return classElements;
}
Usage:
alert(allSpans[i]);
var userSpan = getElementsByClass('myclass', allSpans[i], 'span');
alert(userSpan);
alert(allSpans[i]);
Alerts:
1. [object HTMLSpanElement]
2. [object HTMLSpanElement]
3. undefined
Question:
What is causing the object to be undefined? I am not modifying it anywhere inside the function, just accessing it. The behaviour is consistent in both IE and FF.
To solve this, simply use the var keyword in your for loop e.g.
for (var i = 0, var j = 0 ...
which is just good practice anyway :)