开发者

Removing top-level items from a jQuery set

开发者 https://www.devze.com 2023-01-24 02:17 出处:网络
I c开发者_JAVA百科an\'t find a way to remove top-level items from a jQuery set. Here is my attempt:

I c开发者_JAVA百科an't find a way to remove top-level items from a jQuery set. Here is my attempt:

<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
    <script>
        $(function() {
            var data = '<div id="node_1">aa</div> <div id="node_2">bb</div> <div id="node_3">cc</div>';
            var nodes = $(data);
            nodes.remove("#node_2");
            $("#container").append(nodes);
        });
    </script>
</head>
<body>
    <div id="container"> </div>
</body>
</html>

I expected the following in the container:

<div id="container">
    <div id="node_1">aa</div>
    <div id="node_3">cc</div>
</div>

But the node #2 is not removed.

How can I remove node #2 before inserting it into the document ?


Apparently you cannot remove DOM nodes that are not in the DOM at the moment.

You could use:

nodes = nodes.not('#b');

Keep in mind that even after (and during) manipulation, ids should be unique.


EDIT - Updated to support not inserting the div's into the DOM, and simply removing them pre-insertion.

<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
    <script>
        $(function() {
            var data = '<div class="1">aa</div> <div class="2">bb</div> <div class="3">cc</div>';
            $("#container_1").append(data);
            var nodes = jQuery(data).not('.2');   
            // In this example it's '.2',  
            // though you changed your id's in the original to something else
            $("#container_2").append(nodes);
        });
    </script>
</head>
<body>
    <div id="container_1"> </div>
    <div id="container_2"> </div>
</body>
</html>
0

精彩评论

暂无评论...
验证码 换一张
取 消