Javascript - getElementID from scratch using BFS?

2019-08-22 02:52发布

问题:

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/

Code:

var nodes = [];

function getElementById(node, id) {
    alert(nodes.length);
        if (node.childNodes[i].id == id) {
            return node.childNodes[i];
        } else if (node.childNodes[i].length > 0) {
          for (var i = 0, len = node.childNodes.length; i < len; ++i) {
            nodes.push(node.childNodes[i]);
          }
        }
    if (nodes.length > 0) {
      getElementById(nodes[0], id);  
    }
}

var el = getElementById(document.body, 'id');

Any help?

回答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:

function getElementById(node, id) {
    //An array of all the nodes at the same depth
    var nodes = [node];

    //While the array is not empty
    while(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
    }
}