Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .remove() with selector doesn't work

According to the .remove() | jQuery API Documentation, it is perfectly valid to include a selector as an optional parameter to .remove(). Quote:

We can also include a selector as an optional parameter. For example, we could rewrite the previous DOM removal code as follows:

$( "div" ).remove( ".hello" );

So I've written 2 divs to test this out:

<div id="div1">test
    <div id="div2">Remove</div>
</div>

Using this as jQuery:

$( document ).ready(function() {
    $( "#div1" ).remove( "#div2" );
});

It didn't remove the div as expected. The result was:

test
Remove

Instead using:

$( document ).ready(function() {
    $("#div2").remove();
});

Removes the div as expected. So what am I missing here? Is the documentation wrong? Did I misunderstood something?

like image 242
icecub Avatar asked Sep 28 '15 23:09

icecub


1 Answers

You're misunderstanding what the selector parameter is doing. It is filtering the first set of objects.

From the docs:

A selector expression that filters the set of matched elements to be removed.

So, your "#div2" selector doesn't exist as a part of the "#div1" element. For example, say I have the following:

<div class="red">Red</div>
<div class="red">Red</div>
<div class="red">Red</div>
<div class="red notneeded">Red</div>
<div class="red notneeded">Red</div>
<div class="red">Red</div>

Then, I call the following:

$(function () {
  $("div.red").remove(".notneeded");
});

I would be left with the following:

<div class="red">Red</div>
<div class="red">Red</div>
<div class="red">Red</div>
<div class="red">Red</div>

So, the jQuery matched set is all divs with a class of red - the second selector (".notneeded") will filter that first matched set by the ones with a class of notneeded - then it will remove them.

like image 192
swatkins Avatar answered Oct 04 '22 06:10

swatkins