How to append inner-html from a div to a target div?

Viewed 323

I need to append html from a div to a target div. Can it be done by jQuery?

I have tried some jQuery. but it didnt respond.

$(".categories_box").clone().end().appendTo(".target-div");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="categories_box">
  <ul>
    <li><a href="JavaScript:void(0)">Technology <span>37</span></a></li>
    <li><a href="JavaScript:void(0)">Lifestyle <span>04</span></a></li>
    <li><a href="JavaScript:void(0)">Service <span>29</span></a></li>
    <li><a href="JavaScript:void(0)">Food <span>15</span></a></li>
    <li><a href="JavaScript:void(0)">Architecture <span>09</span></a></li>
    <li><a href="JavaScript:void(0)">Adventure <span>44</span></a></li>
  </ul>
</div>

<div class="target-div"></div>

I have tried to append the entire "<ul>" to the "target-div". But it didn't respond yet.

4 Answers

You can use .html() from jquery like this:

$(".target-div").html($(".categories_box").html());

Use $(".categories_box").clone().appendTo(".target-div"); The .end() is used to

End the most recent filtering operation in the current chain and return the set of matched elements to its previous state.

Most of jQuery's DOM traversal methods operate on a jQuery object instance and produce a new one, matching a different set of DOM elements. When this happens, it is as if the new set of elements is pushed onto a stack that is maintained inside the object. Each successive filtering method pushes a new element set onto the stack. If we need an older element set, we can use end() to pop the sets back off of the stack.

So what you really need is to append the cloned elements.

* UPDATE *

To append only the children:

$(".categories_box").children().clone().appendTo(".target-div");

You can try this.

$(".target-div").html($(".categories_box").html());

The only you have to change your js code.

//$(".categories_box").clone().end().appendTo(".target-div");
$(".target-div").append($(".categories_box").clone().find('ul'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="categories_box">
   <ul>
       <li><a href="JavaScript:void(0)">Technology <span>37</span></a></li>
       <li><a href="JavaScript:void(0)">Lifestyle <span>04</span></a></li>
       <li><a href="JavaScript:void(0)">Service <span>29</span></a></li>
       <li><a href="JavaScript:void(0)">Food <span>15</span></a></li>
       <li><a href="JavaScript:void(0)">Architecture <span>09</span></a></li>
       <li><a href="JavaScript:void(0)">Adventure <span>44</span></a></li>
    </ul>
</div>
        
<div class="target-div"></div>

Related