Maximilian Neuse
Maximilian Neuse

Reputation: 163

Loop function class name with jquery

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

Upvotes: 0

Views: 43

Answers (2)

Nitigna Raval
Nitigna Raval

Reputation: 1

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.

Upvotes: 0

Nikhil Aggarwal
Nikhil Aggarwal

Reputation: 28465

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.

Upvotes: 1

Related Questions