I have an array. What is simple way to loop array and display value in paragraph putting one in each line
A:
Like this?
var a = ['john', 'went', 'to'], p = $('<p>')
$(a).each(function() {
$(p).text( $(p).text() + ' ' + this );
});
$.trim( $(p).text() )
$(p).appendTo('body')
// You want "\n" for a newline and "<br/>" for a line break element.
Pure DOM:
document.body.appendChild( (document.createElement('p')).appendChild( document.createTextNode(['john ', 'went'].join('<br>') )) )
meder
2009-09-22 05:19:33
+1
A:
Since you have an array and want to separate the values with a <br>
, you can simply join
the values:
var arr = ["foo", "bar", "baz"],
elem = /* refers to the paragraph */;
elem.innerHTML = arr.join("<br>");
And with DOM methods only:
var i = 0,
n = arr.length;
if (n) {
elem.appendChild(document.createTextNode(arr[i++]));
while (i < n) {
elem.appendChild(document.createElement("br"));
elem.appendChild(document.createTextNode(arr[i++]));
}
}
Gumbo
2009-09-22 05:20:29
p already exists. When i print like this $("#pop").innerHTML = arr.join("<br>"); nothing happen?
Mario
2009-09-22 05:24:34
$('#pop') is a jQueryized object. You can do $('#pop').text( arr.join('<br>') ) or $('#pop').get(0).innerHTML = arr.join('<br>')
meder
2009-09-22 05:25:41
thank you when i do $('#pop').text( arr.join('</br>') ) it printing </br> also..i want to render into break not print it
Mario
2009-09-22 05:29:16
Use the `html` method instead: `$('#pop').html(arr.join('<br>'))`.
Gumbo
2009-09-22 05:31:00
this is very very very good.Can i also clearify content of pop before adding new val? $('#pop').text('')?
Mario
2009-09-22 05:35:18