brandoncalvin
brandoncalvin

Reputation: 57

Iterate over array and use elements as data attributes

How do I loop through an array and add the elements of the array to the data attribute of the spans inside a div?

html

<div id="wordBank">
    <span>Play</span>
    <span>Game</span>
</div>

jQuery

var words = ["play", "game"];

$.each(words, function(index, value){
    $("#wordBank span").each(function(){
        $(this).attr('data-word', value);
    });
});

Current output

<div id="wordBank">
    <span data-word="game">Play</span>
    <span data-word="game">Game</span>
</div>

Desired output

<div id="wordBank">
    <span data-word="play">Play</span>
    <span data-word="game">Game</span>
</div>

Upvotes: 1

Views: 144

Answers (1)

Maheer Ali
Maheer Ali

Reputation: 36594

You just need to loop on single array and access the value on corresponding index. You don't need a nested loop here.

var words = ["play", "game"];


$("#wordBank span").each(function(index){
    $(this).attr('data-word', words[index]);
});
  
console.log(document.querySelector('#wordBank').outerHTML)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="wordBank">
    <span>Play</span>
    <span>Game</span>
</div>

Upvotes: 2

Related Questions