What is the best way to remove the first div inside the 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 that works fine:

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

Is this the best way to remove the first component? Or is it more efficient to use a selector? An example will be great!

Pay attention . I know I can use:

 $('#divToRemove').remove(); 

however, I would like to be able to use selectors in this case (reasons beyond the scope of the question).

Thanks OK.

+6
source share
6 answers

This should be the fastest and safest:

 $('#parent').find('div').first().remove(); 
+15
source

Do you want to

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

or it will delete all the <div> inside the parent <div> .

+3
source

let's say. you are making a JS event and you have access to "this" I will do it like this.

 $('#child').click(function(){ $(this).closest('div#parent').children('div:first').remove(); }); 

specify that this is not the most efficient way, but useful in an interactive event. alternatively, you can use several selectors:

 //closest,parent,next,prev,find,children and nth-child() 
+2
source

you can try this. It works great for me

.

$ ('# parent) find (' DIV: first '). Delete ();

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

use this if you are only talking about removing the immediate child divs of the parent. and it will be better than .find () when you have more internal divs.

0
source

I have one more:

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

">" selects the child elements of the element that are referenced to the left, and, of course, the "first" refers to the first child.

0
source

Source: https://habr.com/ru/post/891785/


All Articles