javascriptappendinsertafter

How to append a span as the last object in an li?


I currently have this line of code

<div id="news-articles">
  <ul class="display-posts-listing">
    <li class="listing-item">
      <span></span>
      <span class="category-display"></span>
      <span></span>
      <span></span>
    </li>
  </ul>
</div>

I need it to look like this (* note - There are multiple uls. Therefore it has to be each "span.category-display" thats gets appended last inside their own parent li) :

//Ive been trying to use this js script, but so far no results. Can anyone assist? Thanks so much! :





  $("#news-articles .category-display").each(function() {
                $(this).prev("li.listing-item").append(this);
        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="news-articles">
  <ul class="display-posts-listing">
    <li class="listing-item">
      <span></span>
      <span></span>
      <span></span>
      <span class="category-display"></span>
    </li>
  </ul>
</div>


Solution

  • $.prev() selects the previous sibling. You want to use $.parent()

    I would write it like this instead:

    $(".listing-item").each(function(){
        $this = $(this);
        var $elem = $this.find(".category-display").detach();
        $elem.appendTo($this);
    });