4

How can I remove the foo label as well as the div child element and the 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?

O P
  • 2,327
  • 10
  • 40
  • 73

6 Answers6

14

Very simple:

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

So easy...

user3670058
  • 141
  • 1
  • 3
10

Just did on what html you posted here.

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():

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

fiddle for .nextUntil()

Jai
  • 74,255
  • 12
  • 74
  • 103
1

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

Check This for reference

Community
  • 1
  • 1
deXter
  • 354
  • 4
  • 21
1
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..
}
sasi
  • 4,192
  • 4
  • 28
  • 47
0

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

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

CSS adjacent sibling selector.

Dane Hillard
  • 890
  • 1
  • 11
  • 27
0

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('div')  //if you have a parent container as div.
Mr_Green
  • 40,727
  • 45
  • 159
  • 271