简体   繁体   中英

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

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();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM