Umair Jameel Umair Jameel - 2 months ago 6
CSS Question

Fetch and append element at last using jQuery

I have a div parent element with class .carousel-inner. Within this parent div, there are some children elements. I want to take its 2nd (child) element and append that element at last. I am getting and appending second element like this.

var a = $(".carousel-inner").children()[1];
$(".carousel-inner").append(a);


Now as I append this element, it removes this element from second position and append at the last. I want to keep this element a the second position as well. How can I do it?

Answer

using clone() after you find the element. and make another variable

var a = $(".carousel-inner").children()[1],
    b = $(a).clone();
$(".carousel-inner").append(b);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="carousel-inner">
    <div class="child">
    a
    </div>
      <div class="child">
    this clones
    </div>
      <div class="child">
    c
    </div>
</div>

OR clone the element just before appending like so :

var a = $(".carousel-inner").children()[1]
$(a).clone().appendTo('.carousel-inner');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="carousel-inner">
    <div class="child">
    a
    </div>
      <div class="child">
    this clones
    </div>
      <div class="child">
    c
    </div>
</div>

Comments