Question

Given a DOM element.

How can I make a BFS so that, for all its children ( and children of children and so on...) I can find at which level it is found an <a> element that satisfies the href attribute is equal to X. Being X an array of possible values.

Here is what I have so far, but I am failing to see how/when increase a depth variable:

function findAnchorBFS(element) {
    if (element.nodeName == 'A' && isHrefHost(element.href)) {
        return 0; // this is the main level
    }

    var elements = [element];
    var level = 0;

    while (elements.length) {
        var newElements = [];
        for (var i=0; i < elements.length; i++) {
            var children = elements[i].children;
            for (var j=0; j < children.length; j++) {
                var child = children[j];
                if (child.nodeName == 'A' && isHrefHost(child.href)) {
                    return true;
                }
                newElements.push(child);
            }
        }
        elements = newElements;
    }

}
Was it helpful?

Solution

Here is your code modified to record depth:

function findAnchorBFS(element) {
    if (element.nodeName == 'A' && isHrefHost(element.href)) {
        return 0; // this is the main level
    }

    var elements = [{ el: element, depth: 0 }];

    while (elements.length) {
        var newElements = [];
        for (var i=0; i < elements.length; i++) {
            var newDepth = elements[i].depth + 1;
            var children = elements[i].el.children;
            for (var j=0; j < children.length; j++) {
                var child = children[j];
                if (child.nodeName == 'A' && isHrefHost(child.href)) {
                    return newDepth;
                }
                newElements.push({ el: child, depth: newDepth });
            }
        }
        elements = newElements;
    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top