Mario
Mario

Reputation:

loop and list values

I have an array. What is simple way to loop array and display value in paragraph putting one in each line

Upvotes: 0

Views: 105

Answers (2)

Gumbo
Gumbo

Reputation: 655189

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++]));
    }
}

Upvotes: 1

meder omuraliev
meder omuraliev

Reputation: 186552

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>') )) )

Upvotes: 0

Related Questions