Search code examples
javascriptjqueryclonereverse

How to clone -> reverse -> and prependTo?


I have a list of element e.g.: .title, I'm cloning them out and append them to a container, but the order is reversed from prependTo`.

How do I put these cloned element to an array and reverse it before prepending them?

For example, for each .title clone it, and prependTo .container, and wrap it with li:

$('.title').each(function() {
     $this.clone()
          .prependTo('.container')
          .wrap('<li></li>')
});

Solution

  • Given this html:

    <ul>
        <li class="title">A</li>
        <li class="title">B</li>
        <li class="title">C</li>
        <li class="title">D</li>
        <li class="title">E</li>
    </ul>
    
    <ul class="container">        
    </ul>
    

    Use this jQuery to add them to the .container element:

    $('.title').each(function() {
        $('.container')
            .append($(this).clone());
    });
    

    If you want to reverse the order, then use .prepend instead of .append.

    Check out http://jsfiddle.net/y8Aub/ if you want to see it in action.