EDIT
OP has requested the behavior under the condition of viewport size (window width) being that the clones are present when at 600px or less.
How would you use this functions inside a responsive function, to copy it if the window loads/resizes under 600px, and remove it if it resizes to over 600px again? If i wrap it in this: $(window).on("load resize",function(e){ if ($(window).width() < 1200) { } });
It keeps firing for each resize.
While this should be another question entirely, I have added this solution in reply to OP's comment/question. The following PLUNKER uses one media query and the extra styles are for demonstration purposes only. The relevant addition is one media query with one ruleset:
@media (min-width:600px) {
.content + .content > .item > .copy-this {
display: none;
}
}
ORIGINAL ANSWER
First we collect all .copy-this
with .each()
method:
$('.copy-this').each(function(idx, obj) {
Next, we need to differentiate the 2 .content
divs in order to designate which one we need to clone the content from and which one to append the clones to (without modifying layout assuming that a criterion), we can use the adjacent sibling selector +
. With a solid hook into the target elements we will append to, we'll use .eq(idx)
to sync the .item
s from the first .content
, to the .item
s of the last .content
.
var target = $('.content + .content > .item').eq(idx);
Finally, we .clone()
and .prepend()
. Note the results in that the clones are highlighted with yellow text on black background.
var clone = $(this).clone(true, true);
target.prepend(clone);
SNIPPET
$('.copy-this').each(function(idx, obj) {
var target = $('.content + .content > .item').eq(idx);
var clone = $(this).clone(true, true);
target.prepend(clone);
});
.content + .content > .item > .copy-this {
color: yellow;
background: black;
}
.random-div {
color: brown;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="content">
<div class="item">
<div class="copy-this">Some info 1[#1]</div>
<div class="random-div">Not to copy 1[#1]</div>
</div>
<div class="item">
<div class="copy-this">Some info 2[#1]</div>
</div>
<div class="item">
<div class="copy-this">Some info 3[#1]</div>
<div class="random-div">Not to copy 2[#1]</div>
</div>
<div class="item">
<div class="copy-this">Some info 4[#1]</div>
</div>
</div>
<div class="content">
<div class="item">
</div>
<div class="item">
<div class="random-div">This is original content[#2]</div>
</div>
<div class="item">
</div>
<div class="item">
</div>
</div>
</body>