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
Remove child element
提问by O P
How can I remove the foolabel
as well as the div
child 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 posted
here.
就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
and even a better one with .nextUntil()
:
甚至更好的.nextUntil()
:
$('label:contains("qux")').nextUntil($('label:contains(bar)'),$('label, br')).remove();
回答by user3670058
Very simple:
很简单:
$(element).children().remove();
$(element).children().remove();
So easy...
太简单...
回答by deXter
回答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..
}