2

I understand that for a web page's node stored in a variable named 'parent', I can obtain all its child nodes using the command

var children=parent.childNodes;

I have 2 questions here--

(a) Will the above line of code only provide the nodes that are immediate children? Or will nodes even lower than immediate children also be stored in 'children' variable?

(b) How can I parse through each node in the 'children' variable?

4

3 に答える 3

1

1)直接の子のみを返しますが、それらの子ノードにはすべての子ノードが含まれます...など。

2)

for(var i=0;i<children.length;i++)
{
    children[i].......
}
于 2012-07-31T15:51:18.120 に答える
1

a)直接の子のみを返します(ただし、もちろん、各子には子が含まれる場合があります)

b)

var children = parent.childNodes;

for(var i = 0; i < children.length; i++) 
{
    var singleChild = children[i]
}
于 2012-07-31T15:53:31.343 に答える
0

a)はい、直接の子ノードのみがリストされます

b)たとえばES5マジックを使用する

[].forEach.call(children, function( node ) {
    console.log( node );
});

したがって、すべての子ノードをループするために、再帰呼び出しを行うことができます。

(function _loop( current ) {
    [].forEach.call( current.children, function( node ) {
        if( node.children.length ) {
            _loop( node );
        }
        else {
           console.log( node );
        }
    });
}( children ));
于 2012-07-31T15:52:20.783 に答える