Javascript-ONLY DOM Tree Traversal - DFS and BFS?

前端 未结 3 618
小鲜肉
小鲜肉 2021-02-05 14:38

Can anyone provide either code, pseudocode, or even provide good links to implementing DFS and BFS in plain JavaScript (No JQuery, or any helper libraries)? I\'ve been trying to

3条回答
  •  北荒
    北荒 (楼主)
    2021-02-05 15:06

    DFS:

    function m(elem) {
        elem.childNodes.forEach(function(a) {
            m(a);
        });
        //do sth with elem
    }
    m(document.body);
    

    This loops through all elements, and for each element through each child's and so on.

    BFS:

    var childs = [];
    
    function m(elem) {
        elem.childNodes.forEach(function(a) {
            childs.push(a);
        });
        b = childs;
        childs = [];
        b.forEach(function(a) {
            m(a);
        });
    }
    m(document.body);
    

    This loops through the elements, pushes their children onto a stack, and starts again with each of them. As you can see, this consumes much more space (the child's array) which is not the best...

提交回复
热议问题