14

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.

6 Answers 6

26

This should be the fastest and safest:

$('#parent').find('div').first().remove();
4

You want

$('#parent').find('div:first').remove();

or it will remove all <div> within the parent <div>.

2

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

you can try this. It work perfectly on me

$('#parent').find('div:first').remove();

0
$('#parent').children('div:first').remove();

use this if you're only talking about removing immediate children div of parent. and it will be better than .find() when you have more inner divs.

0

Ive got another one:

$('#parent > div:first').remove();

The '>' selects children of the element referenced to the left, and of course ':first" refers to the first child.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.