开发者

How to remove elements except any specific id

开发者 https://www.devze.com 2023-03-30 08:38 出处:网络
let say there is a parent id which contains many elements and 开发者_开发百科i want to remove all elements except one.

let say there is a parent id which contains many elements and 开发者_开发百科i want to remove all 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>

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


$("#parent_id").children(":not(#id_n)").remove();


$("#parent_id > :not(#id_n)").remove();


No jQuery required:

const parent = document.querySelector('#parent_id');
const keepElem = document.querySelector('#id_n');
                
[...parent.children]
  .forEach(child => child !== keepElem ? parent.removeChild(child) : null);


I think the Attribute Not Equals selector makes sense here.

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

Demo.


For fun, POJS is a tad more code, but no jQuery :-)

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

A lot faster too. ;-)


Deleting all children other than id_n with jQuery:

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

If you'are going to delete the parent_id as well:

$('#id_n').insertAfter('#parent_id');
$('#parent_id').remove();
0

精彩评论

暂无评论...
验证码 换一张
取 消