joe witt joe witt -4 years ago 63
Javascript Question

Use jQuery to append <li> items from one <ul> to new <ul>

I have a problem when appending one set of li items from one

ul
to new
ul
.

When I move one it is fine, but when I move two my code duplicates them.

So when I move A & B I get A A B B in the new
ul
instead of A B and I cannot see why.

Here is my JavaScript:

function moveItems(origin, destination){
var highlighted = document.querySelectorAll("#leftlist .highlight");
highlighted.forEach(function(){
$(origin).clone(true).appendTo(destination);
$("#leftlist .highlight").remove();

}
$("#moveright").click(function(){
moveItems(".highlight", "#rightlist");
});


Here is my HTML:

<ul id="leftlist" class="list-group list-group-flush">
<li class="list-group-item">a item</li>
<li class="list-group-item">b item</li>
<li class="list-group-item">c item</li>
<li class="list-group-item">d item</li>
<li class="list-group-item">e item</li>
<li class="list-group-item">f item</li>
<li class="list-group-item">g item</li>
<li class="list-group-item">h item</li>
<li class="list-group-item">i item</li>
<li class="list-group-item">j item</li>
</ul>
</div>
</div>
<ul id="rightlist" class="list-group list-group-flush">
</ul>

Answer Source

In your forEach you have to use the element and not origin

I've changed the following:

highlighted.forEach(function(thisObj) {
    $(thisObj).clone(true).appendTo(destination);

function moveItems(origin, destination) {
  var highlighted = document.querySelectorAll("#leftlist " + origin);
  highlighted.forEach(function(thisObj) {
    $(thisObj).clone(true).appendTo(destination);
    $("#leftlist " + origin).remove();

  })
}
$("#moveright").click(function() {
  moveItems(".highlight", "#rightlist");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="leftlist" class="list-group list-group-flush">
  <li class="list-group-item highlight">a item</li>
  <li class="list-group-item highlight">b item</li>
  <li class="list-group-item">c item</li>
  <li class="list-group-item">d item</li>
  <li class="list-group-item">e item</li>
  <li class="list-group-item">f item</li>
  <li class="list-group-item">g item</li>
  <li class="list-group-item">h item</li>
  <li class="list-group-item">i item</li>
  <li class="list-group-item">j item</li>
</ul>
<ul id="rightlist" class="list-group list-group-flush">
</ul>
<button id="moveright"> moveright </button>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download