0

I have to following code:

$( ".content.one" ).clone().appendTo( ".cat.one .details" );
$( ".content.two" ).clone().appendTo( ".cat.two .details" );
$( ".content.three" ).clone().appendTo( ".cat.three .details" );

I wanted to loop this like

var obj = {
one: 'one',
two: 'two',
three: 'three'
};
$.each(obj, function (index, value) {
  $( ".content.(value)" ).clone().appendTo( ".cat.(value) .details" );
});

But I can't find out how to use the "value" inside the classes

2 Answers 2

1

Use Template literals

var obj = {one: 'one',two: 'two',three: 'three'};

$.each( obj, function( key, value ) {
  $(`.content.${value}`).clone().appendTo(`.cat.${value} .details`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<div class="content one">One</div>
<div class="content two">Two</div>
<div class="content three">Three</div>

<br/>
<div class="cat one"><div class="details"></div></div>
<div class="cat two"><div class="details"></div></div>
<div class="cat three"><div class="details"></div></div>

Note: obj is an object and as per jQuery.each, callback will be passed key and value as arguments rather than index and value.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes perfect. But there is one problem. The background of my code is, I want to copy content elements in categories. Content can also have 2 or more categories, so can appear in different categories. But now if one has 2 or more categories (one, two, three) it appears double. See the full codepen: codepen.io/anon/pen/pmvzgY - see in my example, "Content 2a, 1e" appears 2x in Category 2
It is happening because, during 1st iteration for one, element with both one and two classes has been copied inside category. Now, when you run it for two, there are 2 elements matching the search criteria. You can update the selection to $(.hidden .content.${value}) to avoid the duplicate copies. For reference - codepen.io/anon/pen/mYybaj
0

You can use the code given below.

$(".content ." + value).clone().appendTo(".cat ." + value + " .details");

If the it dosen't help request to share entire code.

2 Comments

thanks, but unfortunalety it is not working: codepen.io/anon/pen/vwEBaR - I am trying to categorized content-divs. The codepen should it make a bit clearer
sorry. the issue is with the spaces in the script. Check the working codepen script codepen.io/nitigna09/pen/QRbKLK

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.