Forum Moderators: open

Message Too Old, No Replies

getElementsByClass()

passing an object, becomes unusable after

         

moltar

1:11 am on Apr 25, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Function:


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.

daosmith

5:55 am on Apr 25, 2006 (gmt 0)

10+ Year Member



I haven't analysed your code in any detail, but from the looks of it the problem is that i is a global variable. Thus when you execute getElementsByClass the value of i gets incremented until it goes past the end of the array and this value carries over even after the function exits. So when you try to access allSpans[i] subsequent to calling getElementsByClass, you are requesting a non-existent element!

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 :)

Moby_Dim

6:39 am on Apr 25, 2006 (gmt 0)

10+ Year Member



Just tested - seems works fine, no undefs at all ;)

moltar

10:08 am on Apr 25, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Yes, the problem was with the "i" variable! I forgot to declare it and used it in both, calling and caller functions. Thanks a lot!