3

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,167
  • 10
  • 36
  • 71

6 Answers6

12

Very simple:

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

So easy...

user3670058
  • 121
  • 1
  • 3
9

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
  • 72,925
  • 12
  • 73
  • 99
1

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

Check This for reference

Community
  • 1
  • 1
deXter
  • 254
  • 3
  • 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
  • 3,886
  • 4
  • 26
  • 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
  • 850
  • 1
  • 11
  • 25
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
  • 39,139
  • 43
  • 154
  • 250