Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.innerHTML <br> breaking

Why is this breaking? I've not used .innerHTML correctly before and don't know why this would be wrong.

function asdf() {
    document.getElementById("qwerty").innerHTML="A<br>
      B<br>
      C<br>
      D<br>";
}
like image 925
Kevin Banas Avatar asked Sep 24 '13 19:09

Kevin Banas


People also ask

How do you do a line break in innerHTML?

Because you are outputting to HTML, you need to think HTML. In HTML, a new line is done with the tag <br/> .

Is innerHTML a security risk?

Setting the value of innerHTML lets you easily replace the existing contents of an element with new content. Note: This is a security risk if the string to be inserted might contain potentially malicious content.

What does .innerHTML return?

The innerHTML property returns: The text content of the element, including all spacing and inner HTML tags. The innerText property returns: Just the text content of the element and all its children, without CSS hidden text spacing and tags, except <script> and <style> elements.

What is the difference between innerText and innerHTML?

innerText returns all text contained by an element and all its child elements. innerHtml returns all text, including html tags, that is contained by an element.


2 Answers

You have to escape new-lines in JavaScript string-literals:

function asdf() {
    document.getElementById("qwerty").innerHTML="A<br>\
      B<br>\
      C<br>\
      D<br>";
}

Though you could, potentially more-easily, simply insert newlines in the string itself:

function asdf() {
    document.getElementById("qwerty").innerHTML = "A<br>\nB<br>\nC<br>\nD<br>";
}
like image 136
David Thomas Avatar answered Nov 09 '22 12:11

David Thomas


Javascript string literals cannot contain newlines.

You can escape the newlines with backslashes:

var myString = "a\
b";
like image 27
SLaks Avatar answered Nov 09 '22 12:11

SLaks