Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery, How to print text twice using a for loop?

Tags:

jquery

What am I doing wrong here?


I have the following code:

HTML:

<div></div>

jQuery:

for(var i = 0; i < 2; i++){
  console.log('test');
  $('div').text('sometext ');
}

My Output:

sometext

What I expect:

sometext sometext

Why does this not print the text to the div twice?

like image 886
Kris Hollenbeck Avatar asked Dec 06 '25 14:12

Kris Hollenbeck


1 Answers

Use .append()

.text replaces the previous content.

for(var i = 0; i < 2; i++){
  console.log('test');
  $('div').append('sometext');
}

Check Fiddle

Or

If you really want to use text you can do this

var html = '';
for(var i = 0; i < 2; i++){
  console.log('test');
  html += 'sometext ';
}
$('div').text(html);

Fiddle 2

Store the text in a variable and then use text after the for loop.

like image 112
Sushanth -- Avatar answered Dec 08 '25 18:12

Sushanth --



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!