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>
Vitalii
1,0101 gold badge10 silver badges16 bronze badges
asked Mar 15, 2018 at 8:36
Honzík Azjol Havelka
3252 silver badges14 bronze badges
2 Answers 2
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>
answered Mar 15, 2018 at 8:38
Ankit Agarwal
30.8k5 gold badges41 silver badges63 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
- You can use for loop.
- 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>
answered Mar 15, 2018 at 8:41
guradio
15.6k4 gold badges39 silver badges65 bronze badges
Comments
Explore related questions
See similar questions with these tags.
lang-js