How to delete items except for a specific identifier

let's say there is a parent id that contains a lot of elements, and I want to delete all the elements except one.

ex .:

<div id = "parent_id"> <div id = "id_1"> <div id = "id_11"> </div> <div id = "id_11"> </div> </div> <div id = "id_2"> </div> <div id = "id_n"> </div> // No need to remove this id_n only </div> 

How can I remove innerHTML like this document.getElementId('parent_id').innerHTML = ''; but I do not need to remove id_n . is there any way to do this using javascript or jQuery.

+4
source share
5 answers
 $("#parent_id").children(":not(#id_n)").remove(); 
+7
source
 $("#parent_id > :not(#id_n)").remove(); 
+2
source

I think the Attribute Not Equals selector makes sense here.

 $("#parent_id div[id!='id_n']").remove(); 

Demo version

+2
source

For fun, POJS is some more code, but not jQuery :-)

 var p = document.getElementById('parent_id'); var d = document.getElementById('id_n'); p.innerHTML = ''; p.appendChild(d); 

Much faster .; -)

+2
source

Removing all children other than id_n with jQuery:

 $('#parent_id div').not('#id_n').remove(); 

If you are also going to remove parent_id:

 $('#id_n').insertAfter('#parent_id'); $('#parent_id').remove(); 
+1
source

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


All Articles