jQuery 移除子元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15016867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:14:24  来源:igfitidea点击:

Remove child element

jquery

提问by O P

How can I remove the foolabelas well as the divchild element and the br's?

如何删除foolabel以及div子元素和br's?

<label>qux</label>
<label>foo</label><div id="block">text</div><br /><br />
<label>bar</label>

My current makeshift method:

我目前的临时方法:

$('label:contains("foo")').next().remove();
$('label:contains("foo")').remove();

How can I improve upon this?

我该如何改进?

回答by Jai

Just did on what html you postedhere.

did on what html you posted在这里。

Try this:

尝试这个:

 $('label:contains("foo")').remove(); // <-----------label contains foo removed
 $('#block').remove(); //<---------------------------div with id 'block' removed
 $('label:contains(qux)').nextAll('br').remove(); //<--finally all the br next to first label removed

checkout on fiddle

在小提琴上结帐

and even a better one with .nextUntil():

甚至更好的.nextUntil()

$('label:contains("qux")').nextUntil($('label:contains(bar)'),$('label, br')).remove();

fiddle for .nextUntil()

.nextUntil()

回答by user3670058

Very simple:

很简单:

$(element).children().remove();

$(element).children().remove();

So easy...

太简单...

回答by deXter

Use .html() method and set it to null.

使用 .html() 方法并将其设置为 null。

Check Thisfor reference

检查这个以供参考

回答by Dane Hillard

I don't see a great way to improve the removal of the foo <label>. You could improve the removal of the div, syntactically, by using

我没有看到改善 foo 删除的好方法<label>。您可以div通过使用在语法上改进 的删除

$('label:contains("foo") + div').remove();

CSS adjacent sibling selector.

CSS 相邻兄弟选择器。

回答by Mr_Green

Try this:

尝试这个:

$('label').each(function(){
    var self = $(this);
    if(self.text() == 'foo'){
          self.next('div').remove();
          self.parent().find('br').remove(); //else use two times next() to remove two br tags.
          self.remove();
    }
});

please mention the parent element inside the .parent(), something like this:

请提及 中的父元素.parent(),如下所示:

parent('div')  //if you have a parent container as div.

回答by sasi

if($("label").text()=='foo'){
   $(this).next('div').remove();
   $(this).closest('br').remove(); 

   // I've used next and closest methods to remove..you can try with others..
}