Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a "new line" in innerHTML

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];
like image 667
Gudron Swiss Avatar asked Oct 17 '13 23:10

Gudron Swiss


People also ask

How do you add a new line in innerHTML?

In HTML, a new line is done with the tag <br/> .

How do you do a line break in HTML?

The <br> HTML element produces a line break in text (carriage-return). It is useful for writing a poem or an address, where the division of lines is significant.

How do you add a new line in JavaScript?

The newline character is \n in JavaScript and many other languages. All you need to do is add \n character whenever you require a line break to add a new line to a string.


2 Answers

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>";
like image 80
Juan Mendes Avatar answered Oct 05 '22 10:10

Juan Mendes


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

Happy Coding!
   - $cr1ptN!nj@

like image 39
cbur Avatar answered Oct 05 '22 10:10

cbur