Rob Myrick Rob Myrick - 8 days ago 5
Javascript Question

jQuery: assign array values to another set of elements

I have this code:

jQuery(document).ready(function($) {
var i = 0;
var values = [];
var element = $('.source');
element.each(function(i) {
values[i++] = $(this).text();
});
});


I want to assign each array value above, as the individual
data-text
value on another set of list elements. Something like this:

<ul id="list">
<li data-text="arrayvalue1"></li>
<li data-text="arrayvalue2"></li>
<li data-text="arrayvalue3"></li>
</ul>


I don't understand how I would do this using jQuery.

Answer

You can use attr() to assign data-text values with values from another array. With each() loop you are iterating over all li elements in ul and adding values from element array starting from 0, and you are also incrementing i by 1. So on second li, value of i will be 1 which is arrayvalue2 etc...

var element = ["arrayvalue1", "arrayvalue2", "arrayvalue3"]

var i = 0;
var values = $('ul li').each(function() {
  return $(this).attr('data-text', element[i++]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="list">
  <li></li>
  <li></li>
  <li></li>
</ul>