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
6 answers
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