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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With