I have the following markup:
<div id="parent">
<div id="divToRemove">
</div>
</div>
And I have the following jQuery to remove the first div which works fine:
$('#parent').find('div').remove();
Is this the best way to remove the first component? Or is it more efficient to use selectors? An example would be great!
Please note, I know I can use:
$('#divToRemove').remove();
however I'd like to be able to use selectors in this instance (reasons outside of scope of question).
Thanks, Norm.
This should be the fastest and safest:
$('#parent').find('div').first().remove();
You want
$('#parent').find('div:first').remove();
or it will remove all <div>
within the parent <div>
.
let's say. you are doing JS event and you have access to "this" I will do it this way.
$('#child').click(function(){
$(this).closest('div#parent').children('div:first').remove();
});
clarify, this is not the most efficient way but useful in interactive event. alternatively, you can make use of a few selector :
//closest,parent,next,prev,find,children and nth-child()
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