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();
});
});
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With