javascriptnodesparent-node

While loop with node and parentNode not reaching end


I'm trying to do a simple loop and check if nodes/parentNode class name matches a string in a array. Code is as follows:

function isInside(list,node) {
    while( node !== undefined ) {
        for( var i = 0; i < list.length; i++ )
            if( node.className.indexOf(list[i]) > -1 )
                return true;
        node = node.parentNode;
    }
    alert(1); // The code does not reach this when false
    return false;
}

Any ideas what is wrong here?


Solution

  • Follow this pattern:

    var current = node;
    while (current.parentNode){
     // do stuff with node
     current = current.parentNode
    
    }