如何使用JQuery删除除第一个div之外的所有子div元素?

时间:2018-04-21 08:53:59

标签: jquery

我有一些子div元素,它是动态创建的。我想删除父节点的所有div元素,除了第一个子节点。

这是我尝试的代码

function someFunction(obj, abc) {
  if ($(obj).children().hasClass("glyphicon-plus")) {
    //There is some code
  } else {
    var classname = abc;
    var mergeFolderName = classname.split(" ");

    var fullClassName = "";

    for (var i = 0; i < mergeFolderName.length; i++) {
      if (i > 0) {
        fullClassName = fullClassName + "-" + mergeFolderName[i];
      } else {
        fullClassName = 'parent-folder-' + mergeFolderName[i];
      }
    }
    alert("After merge = " + fullClassName); //parent-folder-Great-Plains

    if ($(obj).parent().hasClass(fullClassName)) {

      var count = $("." + fullClassName).children().length;
      alert("child div length = " + count); //length = 3


      for (var i = 0; i < count; i++) {
        alert("class NO=" + i + "    Name = " + $("." + fullClassName).children('div:eq(' + i + ')').attr("class"));
        if (i > 0) { //remove 2 and 3
          $("." + fullClassName).children('div:eq(' + i + ')').remove();
        }
      }
    }
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="parent-folder-Great-Plains">

  <div class="MainFolder Great Plains folder-icon" onclick="someFunction(this,'Folder1')" style="padding-left: 20px;">
    <span class="glyphicon glyphicon-minus"></span> Folder1
  </div>
  <div class="MainFolder folder-icon Accounts" onclick="someFunction(this,'Folder2')" style="padding-left:20px;">Folder2</div>
  <div class="MainFolder folder-icon Purchase" onclick="someFunction(this,'Folder3')" style="padding-left:20px;">Folder3</div>
</div>

注意

  

用户将单击Folder1,然后必须删除folder2和folder3。

我的问题是,当用户点击Folder1时,它会移除folder2,但不会移除folder3

更新

  

我不想使用abc = 'Folder1',因为它不会是相同的文件夹名称。我想转到Folder1的父文件夹,然后我想删除父级的所有细分,除了第一个div

1 个答案:

答案 0 :(得分:1)

你可以这样做:

$(obj)                     //Select the object
   .parent()               //Select the parent of the object
   .children()             //Select all the children of the parent
   .not(':first-child')    //Unselect the first child
   .remove();              //Remove

这是一个片段:

&#13;
&#13;
function someFunction(obj, abc) {
  $(obj).parent().children().not(':first-child').remove();
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="parent-folder-Great-Plains">
  <div class="MainFolder Great Plains folder-icon" onclick="someFunction(this,'Folder1')" style="padding-left: 20px;">
    <span class="glyphicon glyphicon-minus"></span> Folder1
  </div>
  <div class="MainFolder folder-icon Accounts" onclick="someFunction(this,'Folder2')" style="padding-left:20px;">Folder2</div>
  <div class="MainFolder folder-icon Purchase" onclick="someFunction(this,'Folder3')" style="padding-left:20px;">Folder3</div>
</div>
&#13;
&#13;
&#13;

Doc:siblings()