Trevor Bollinger
Trevor Bollinger

Reputation: 31

How can I append a <br> using document.getElementByID?

I'm trying to append a <p> element using DOM to append a stock symbol, and stock price, then go to a new line using <br>, but when I run this:

for(var i=0; i<stockPrices.length; i++){
    document.getElementById("stockprice").append(stockNames[i]+" ");
    document.getElementById("stockprice").append(stockPrices[i]+" ");
    document.getElementById("stockprice").append("<br>");
}

it literally adds the text <br> to my "stockprice" element. What is the proper way to do this?

Upvotes: 1

Views: 1634

Answers (2)

Nitheesh
Nitheesh

Reputation: 19986

You should go for innerHTML

function appendContent() {
  document.getElementById("stockprice").innerHTML += "<br>";
  document.getElementById("stockprice").innerHTML += "New Data";
}
<p id="stockprice">Initial Content</p>
<button onclick="appendContent()">Append</button>

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370689

Use insertAdjacentHTML instead:

document.body.append('content');
document.body.insertAdjacentHTML('beforeend', '<br>');
document.body.append('more content');

I'd recommend against concatenating with the existing innerHTML because that will

(1) corrupt existing listeners inside the container, if any, and

(2) force the browser to re-parse the entire contents of the container (in contrast, with insertAdjacentHTML, the browser only parses/inserts what gets added)

Note that you can also save the element in a variable first to avoid repeating yourself:

const stockPriceElm = document.getElementById("stockprice");
for(var i=0; i<stockPrices.length; i++){
  stockPriceElm.append(stockNames[i]+" ");
  stockPriceElm.append(stockPrices[i]+" ");
  stockPriceElm.insertAdjacentHTML('beforeend', "<br>");
}

Or, even better:

const stockPriceElm = document.getElementById("stockprice");
for (var i = 0; i < stockPrices.length; i++) {
  stockPriceElm.insertAdjacentHTML('beforeend', stockNames[i] + " " + stockPrices[i] + " <br>");
}

Upvotes: 4

Related Questions