Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to remove first div inside a parent div using jQuery?

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.

like image 453
enormace Avatar asked Jul 01 '11 04:07

enormace


3 Answers

This should be the fastest and safest:

$('#parent').find('div').first().remove();
like image 141
qwertymk Avatar answered Nov 19 '22 18:11

qwertymk


You want

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

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

like image 39
user122211 Avatar answered Nov 19 '22 17:11

user122211


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()
like image 2
Elliot Yap Avatar answered Nov 19 '22 17:11

Elliot Yap