How to remove elements except any specific id

2020-07-14 12:35发布

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.

5条回答
Deceive 欺骗
2楼-- · 2020-07-14 12:45
$("#parent_id").children(":not(#id_n)").remove();
查看更多
够拽才男人
3楼-- · 2020-07-14 12:45
$("#parent_id > :not(#id_n)").remove();
查看更多
该账号已被封号
4楼-- · 2020-07-14 13:02

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();
查看更多
太酷不给撩
5楼-- · 2020-07-14 13:04

I think the Attribute Not Equals selector makes sense here.

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

Demo.

查看更多
祖国的老花朵
6楼-- · 2020-07-14 13:09

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. ;-)

查看更多
登录 后发表回答