Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicating an image in each container during iteration

I'd like to clone each section's bgimage under the section title without affecting the original image.

Here is my HTML:

<div class="wrapper">
    <div class="section">
        <img class="bgimage" src="imagepath_1.jpg" alt="" />
        <h2>Title</h2>
        <!--clone goes here-->
    </div>
    <div class="section">
        <img class="bgimage" src="imagepath_2.jpg" alt="" />
        <h2>Title</h2>
        <!--clone goes here-->
    </div>
    <div class="section">
        <img class="bgimage" src="imagepath_3.jpg" alt="" />
        <h2>Title</h2>
        <!--clone goes here-->
    </div>
</div>

And my code:

$(document).ready(function($) {
    $('.section').each( function (index, data) {    
        $(this).find('img.bgimage').first().clone().appendTo('.section h2').first();
    });
});
like image 377
Seth Tipton Avatar asked Jan 27 '26 17:01

Seth Tipton


1 Answers

One problem in your code is that appendTo adds a child element to a container. What you really want is insertAfter.

Another problem is that you're not referring to each section in the each function. You should use the second function parameter.

Here is a solution:

$(document).ready(function($) {
  $('.section').each(function (index, section) {    
    var image = $(section).find('img.bgimage').first(),
        title = $(section).find('h2').first();
    image.clone().insertAfter(title);
  });
});
.section {
  border: 1px solid #888;
  margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
    <div class="section">
        <img class="bgimage" src="http://api.jquery.com/jquery-wp-content/themes/jquery/images/logo-jquery.png" alt="" />
        <h2>Section 1</h2>
        <!--clone goes here-->
    </div>
    <div class="section">
        <img class="bgimage" src="http://jquery.com/jquery-wp-content/themes/jquery.com/i/feature-sprites.png" alt="" />
        <h2>Section 2</h2>
        <!--clone goes here-->
    </div>
    <div class="section">
        <img class="bgimage" src="http://jquery.com/jquery-wp-content/themes/jquery/images/jq-nav-icons.png" alt="" />
        <h2>Section 3</h2>
        <!--clone goes here-->
    </div>
</div>
like image 69
Michael Laszlo Avatar answered Jan 30 '26 08:01

Michael Laszlo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!