Behseini
Behseini

Reputation: 6320

Issue On Using Text() in a loop

Can you please take a look at this demo and let me know why I am just getting the last item in the .result

for (i = 0; i < 5; i++) {
   $('.result').text('Hello' + [i]);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="result"></div>

Upvotes: 0

Views: 45

Answers (4)

user2970115
user2970115

Reputation: 483

You can append the source code within a new element.

for (i = 0; i < 5; i++) {
   $('.result').append( $('<p>').text('<p>' + 'Hello' + [i] + '</p>') );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="result"></div>

Upvotes: 2

Tushar
Tushar

Reputation: 87203

text() will replace the innerText of the element. To append the text, you need append().

for (i = 0; i < 5; i++) {
   $('.result').append(' Hello' + [i]);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="result"></div>

To check how text() works,

for (var i = 0; i < 5; i++) {
  (function(i) {
    setTimeout(function() {
      $('.result').text(' Hello' + [i]);
    }, 1000 * i);
  }(i));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="result"></div>

Upvotes: 1

ozil
ozil

Reputation: 7117

Because .text() set the text. It will set

Hello0 // when i=0  
Hello1 // when i=1  
Hello2 // when i=2  
Hello3 // when i=3  
Hello4 // when i=4  

Upvotes: 1

Amar Singh
Amar Singh

Reputation: 5622

You are always changing the content of div and last text changed is hello4

JsFiddle

for (i = 0; i < 5; i++) {
   $('.result').html($('.result').html()+'Hello' + [i]);
}

Upvotes: 0

Related Questions