jquery从另一个元素中移除移除

jquery remove removing from another element

本文关键字:元素 另一个 jquery      更新时间:2023-09-26

根据这里,jquery的remove函数应该像这样工作…

$('div').remove('selector'); 

我在这个例子中尝试。

HTML:

<div class="wrapper">
    <p class="unwanted">This should be removed</p>
    <p class="retained">This will remain</p>
</div>​

JavaScript:

jQuery(document).ready(function($) {
    $('div').remove('p.unwanted'); //not working
    //$('p.unwanted').remove(); //this works
});

​它不起作用。我做错了什么?

您误解了文档中的内容。它不是在寻找与选择器匹配的匹配元素的后代元素,而是简单地将已经匹配的元素集向下过滤到与选择器匹配,然后删除它们。

如果你有这个HTML:

<div class="wanted">Some text</div>
<div class="wanted">Some more text</div>
<div class="unwanted">Some unwanted text</div>

然后执行这个jQuery:

$('div').remove('.unwanted');

那么它将只删除第三个<div>(上面有unwanted类的那个),因为它首先选择所有<div>元素,然后只删除与选择器匹配的元素。

示例jsFiddle

您正试图删除既有div又有p.unwant的内容。remove()中的筛选器应用于当前节点集,在本例中为所有div元素。

改为使用子集:

$('div').children().remove('p.unwanted');

您应该使用以下内容:

$('p').remove('.unwanted');

remove中的参数用作筛选器。因此,在这里,您首先选择所有<p>元素,然后仅移除那些具有类unwanted的元素。

演示:http://jsfiddle.net/qwXSw/1/

尝试这个

 $(document).ready(function() {
    $('div').find('p.unwanted').attr('class', '');
});