Get elements just 1 level below the current element by javascript

后端 未结 8 2008
自闭症患者
自闭症患者 2021-02-05 20:30

I need to access the DOM tree and get the elements just 1 level below the current element.

Read the following code:

相关标签:
8条回答
  • 2021-02-05 21:24

    I'd highly recommend you look at JQuery. The task you're looking to do is straightforward in pure Javascript, but if you're doing any additional DOM traversal, JQuery is going to save you countless hours of frustration. Not only that but it works across all browsers and has a very good "document ready" method.

    Your problem solved with JQuery looks like:

    $(document).ready(function() {
        var children = $("#node").children();
    });
    

    It looks for any element with an id of "node" then returns its children. In this case, children is a JQuery collection that can be iterated over using a for loop. Additionally you could iterate over them using the each() command.

    0 讨论(0)
  • 2021-02-05 21:27

    You could use a function that rules out all non-element nodes:

    function getChildNodes(node) {
        var children = new Array();
        for(var child in node.childNodes) {
            if(node.childNodes[child].nodeType == 1) {
                children.push(child);
            }
        }
        return children;
    }
    
    0 讨论(0)
提交回复
热议问题