1

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>
1
  • 2
    You don't need nested loops. Try to iterate the spans and look up the word by index like words[spanIndex]. Commented Dec 5, 2020 at 3:31

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.