2

Hello I would like to fill gradually span elements with values of array. Can you help me please?

<span class="gt"></span>
<span class="gt"></span>
<span class="gt"></span>

var array=["apple","banana","cucumber"];

$("span.gt").each(function(){
    $(this).text(array[?]);
});

Output should look like this:

<span class="gt">apple</span>
<span class="gt">banana</span>
<span class="gt">cucumber</span>

2 Answers 2

3

You get the index value in the function for each loop. And since the number of span elements is equal to the number of items in the array variable you can use that index value to set the array values in the span elements:

var array=["apple","banana","cucumber"];

$("span.gt").each(function(index){
    $(this).text(array[index]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="gt"></span>
<span class="gt"></span>
<span class="gt"></span>

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

Comments

0
  1. You can use for loop.
  2. Use the increment number as index of the span and index of array

var array = ["apple", "banana", "cucumber"];
for (var i = 0; i < array.length; i++) {
  $('span').eq(i).text(array[i]);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="gt"></span>
<span class="gt"></span>
<span class="gt"></span>

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.