skip to Main Content

I have a divs inside parent div:

<div id="parent">
  <div id="child">some content1</div>
  <div id="child">some content1</div>
</div> 

I get the parent div using jQuery:

var allDivs= $("#parent").html();

I want to remove child divs from this parent, how I can do this? Child divs should be deleted from jQuery object but not from DOM, is it possible?

2

Answers


  1. child divs should be deleted from jquery object but not from dom

    Deleting them from the jQuery object which references the DOM would remove them from the DOM. However, you can clone that object and then modify the clone all you like.

    For example:

    var allDivs = $("#parent").html();
    console.log("all divs: ", allDivs);
    
    var parentDiv = $("#parent").clone().empty().html();
    console.log("only parent: ", parentDiv);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <div id="parent">
      <div class="child">some content1</div>
      <div class="child">some content1</div>
    </div>

    As you can see in the second operation above, after selecting the "parent" you can call .clone() to create an in-memory clone of the structure, then .empty() to remove all child elements from that (in-memory) parent element.


    Edit: If you want to remove only some child elements then instead of .empty() you’d want to specifically target and remove those elements. For example:

    var allDivs = $("#parent").html();
    console.log("all divs: ", allDivs);
    
    var someDivs = $("#parent").clone();
    someDivs.find(".child").remove();
    console.log("some divs: ", someDivs.html().trim());
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <div id="parent">
      <div class="child">some content1</div>
      <div class="child">some content1</div>
      <div class="keep">some content1</div>
      <div class="keep">some content1</div>
    </div>
    Login or Signup to reply.
  2. .empty method should do the trick for you…

    allDivs.empty()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search