soum
soum

Reputation: 1159

making divs as array items and adding to list items

I have the html structure like this, where I am trying to insert each .blueText into each .blue...The divs with class blue is dynamically generated and the task is to add the blueText through JQuery.

<div class="blueText">test 1</div>
<div class="blueText">test 2</div>
<div class="blueText">test 3</div>
<div class="blueText">test 4</div>
<div class="blueText">test 5</div>


<div class="blue"></div>
<div class="blue"></div>
<div class="blue"></div>
<div class="blue"></div>
<div class="blue"></div>

This method works

var blueText = [ 'test 1', 'test 2', 'test 3', 'test 4', 'test 5'];
    $('.blue').each(function (k) {
    $(this).append(blueText[k]);
    });

But how do I make this work instead of hard coding the text as an array

Upvotes: 0

Views: 51

Answers (1)

adeneo
adeneo

Reputation: 318182

To move the .blueText elements inside the .blue elements, you'd do:

var text = $('.blueText');

$('.blue').append(function(i,el) {
    return text.eq(i);
});

FIDDLE

To just append the text from the .blueText elements to .blue :

var text = $('.blueText');

$('.blue').text(function(i) {
    return text.eq( i ).text();
});

Upvotes: 2

Related Questions