Skip to content Skip to sidebar Skip to footer

Javascript - Getelementid From Scratch Using Bfs?

I'm trying to learn javascript, and spent tonight writing a getElementByID() function using Breadth-First Search. In short: I'm lost. Fiddle: http://jsfiddle.net/timdown/a2Fm6/ Cod

Solution 1:

You're missing a for loop in the top half of your code. Where is i defined?

Here's how I'd write it:

functiongetElementById(node, id) {
    //An array of all the nodes at the same depthvar nodes = [node];

    //While the array is not emptywhile(nodes.length) {
        var newNodes = [];
        for(var i = 0; i < nodes.length; i++) {
            var children = nodes[i].childNodes;
            for(var j = 0; j < children.length; j++) {
                var child = children[j];
                if(child.id == id) {
                    return child
                }
                newNodes.push(child);
            }
        }

        //Replace nodes with an array of the nodes the next level down
        nodes = newNodes
    }
}

Post a Comment for "Javascript - Getelementid From Scratch Using Bfs?"