如何选择元素以外的所有子元素

时间:2010-03-26 20:10:13

标签: javascript jquery

我有一个包含3个孩子的元素。让我们说

<div class="parent">

<div class="firstChild">firstChild</div> 
SecondChild
<ul><li>thrid child</li></ul>

</div>

在示例中,我需要选择前2个孩子而不是UL。怎么做jquery。

6 个答案:

答案 0 :(得分:2)

您可以使用:lt选择器。 http://api.jquery.com/lt-selector/*选择器。

$('div.parent > *:lt(2)')

答案 1 :(得分:0)

这个选择器应该这样做。

$(".parent *").not("ul")

答案 2 :(得分:0)

试试这个:

$(".parent").children();

答案 3 :(得分:0)

如果你想要包含文本节点,.clone()它并删除你不想要的东西:

var children = $(".parent").clone();
children.find("ul").remove(); //or: children.find(":gt(1)").remove();
//children now contains everything by the <ul>

答案 4 :(得分:0)

我在原帖中评论了一些关于海报示例标记中实际存在哪些节点的内容 如果有人感兴趣,这里有一些东西可以打印出“真实”的结构。我刚刚向父元素添加了一个id,以便在开始使用DOM时更容易获得它:

<body>

<div id="parent" class="parent">

<div class="firstChild">firstChild</div> 
SecondChild
<ul><li>thrid child</li></ul>

</div>

<script type="text/javascript">
    (function (startNode) {
        // Recursively walking the structure from the supplied node
        function walk(node, indent) {
            indent = (typeof indent==='undefined') ? '' : indent;
            var children = node.childNodes;
            var child, info;
            // For each child of node...
            for (var idx=0, len=children.length; idx<len; ++idx) {
                child = children.item(idx);
                // ..print it.
                printNodeInfo(child, indent);
                // If it was an element (tag) we try to display any children it might have
                if (child.nodeType===1) {
                    arguments.callee(child, indentAdd+indent);
                }
            }
        }
        function printNodeInfo(node, indent) {
            indent = (typeof indent==='undefined') ? '' : indent;
            console.log(indent+getNodePrintString(node));
        }
        function getNodePrintString(node) {
            var info = '';
            // Check type and extract what info to display
            if (node.nodeType===1) {info = node.nodeName;} // element nodes, show name
            else if (node.nodeType===3) {info = trim(node.nodeValue);} // text nodes, show value
            // If it was an empty textnode, return special string
            if (!info) {return '[empty '+nodeTypes[node.nodeType]+' node]';}
            else {return nodeTypes[node.nodeType]+': '+info+(node.id?'#'+node.id:'');}
        }
        // Just a utility function to trim values of textnodes
        function trim(str) {
            return str.replace(/^\s+/, '').replace(/\s+$/, '');
        }
        // Amount of indentation to add each level
        var indentAdd = '    ';
        // Mappings for nodeType => name of nodetype
        var nodeTypes = {
            1: '@Element'
            , 2: '@Attribute' // not used right now
            , 3: '@Text'
        };
        // Print info in start node
        printNodeInfo(startNode);
        // Start walking
        walk(startNode, indentAdd);
    })(document.getElementById('parent')); // Supply a start node

</script>
</body>

这是输出:

@Element: DIV#parent
    [empty @Text node]
    @Element: DIV
        @Text: firstChild
    @Text: SecondChild
    @Element: UL
        @Element: LI
            @Text: thrid child
    [empty @Text node]

答案 5 :(得分:0)

以下是如何获取元素的子节点,包括“纯”文本节点(文本不在标签内)。

// Returns child nodes (including text nodes, if not empty) of 'node',
// but no more than 'limit' nodes.
// If limit given is not a number >= 0, it harvests as many as it can find.
function npupNodes(node, limit) {
    // not a number or < 0 means 'no limit'
    limit = (typeof limit!=='number' || limit<0) ? -1 : limit;
    var result = [];
    var children = node.childNodes;
    var child, nodeType, captureCount=0;
    // Loop over children...
    for (var idx=0, len=children.length; idx<len && (limit<0 || captureCount<limit); ++idx) {
        child = children.item(idx);
        nodeType = child.nodeType;
        // If it is an element or a textnode...
        if (nodeType===1 || nodeType===3) {
            if (nodeType===3 && !child.nodeValue.replace(/^\s+/, '').replace(/\s+$/, '')) {
                // ..if it is a textnode that is logically empty, ignore it
                continue;
            }
            // ..otherwise add it to the harvest, and increase counter
            result.push(child);
            captureCount += 1;
        }
    }
    return result;
}

正如您在代码中看到的那样,不返回逻辑空白(所有空白)文本节点。

通过海报问题中的标记来调用它,它可以完成工作要求(除了不使用jQuery - 起诉我:)

var someChildren = npupNodes(document.getElementsByClassName('parent')[0], 2);