Add a "new line" in innerHTML
Asked Answered
P

3

42

I am trying to create a table with images in first cell and information about the pic in second cell.

I need to add different information in one cell, like that:

cellTwo.innerHTML = arr_title[element] + arr_tags[element];

Is it possible to add a "new line" there? I mean like that:

cellTwo.innerHTML = arr_title[element] + "/n" + arr_tags[element];
Polity answered 17/10, 2013 at 23:13 Comment(3)
yes, it is does not workPolity
HTML newlines are ignored by default. Use <br> tagAnnettannetta
If it helps, innerHTML will store newlines accurately in the DOM. They are only combined with any other whitespace and treated as a single space during rendering.Hawse
U
50

The simplest way is by adding a line break as html

cellTwo.innerHTML = arr_title[element] + "<br />" + arr_tags[element];

If you want your newlines to be treated literally, you could use the <pre> tag

cellTwo.innerHTML = 
    "<pre>" + arr_title[element] + "\n" + arr_tags[element] + "</pre>";
Unnecessary answered 17/10, 2013 at 23:19 Comment(2)
By using <pre> tag, the font size would become very small.Cathey
@zhang I'm not sure what you mean, to you can control the font size with CSSUnnecessary
A
16

To round out your understanding:

Since it is HTML(innerHTML) it renders html and you can use any html you wish, so in this case simply add an good old fashioned <br>:

var test = document.getElementById('someElementId');
test.innerHTML = "The answer <br>to life, the universe, and everything...<br> is 42.";

If it were a string, such as in an alert box or text box etc. then /n would be correct:

alert('Never /n Forget your towel.'); 
Abm answered 28/3, 2014 at 17:20 Comment(0)
S
-3

No, <br /> does not work in asp .net but you can instead write it like so

cellTwo.innerHTML = arr_title[element] + arr_tags[element]; arr_title[element] + "/n" + arr_tags[element];

Edit - alternative wrapped in code tags

cellTwo.innerHTML = arr_title[element] + arr_tags[element];
cellTwo.innerHTML += arr_title[element] + "/n" + arr_tags[element];

Semicolon ";" seems to act as line breaks Remember the "+=" to assign multiple values to the string

Spangler answered 16/7, 2016 at 21:0 Comment(1)
<br /> works perfectly fine in HTML generated from ASP.NET. "/n" doesn't mean a new line anywhere as far as I know. \n means a new line in a JavaScript string literal, but is treated like any other whitespace when converted to HTML. A semicolon does not act like a line break in JavaScript, a semicolon ends a statement. Sometimes a line break with cause a semicolon to be inserted automatically in JS. In short, absolutely everything about this answer is wrong (and mostly the exact opposite of correct)Biddie

© 2022 - 2024 — McMap. All rights reserved.