Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert <br /> in a String in Javascript

Let's say, I have a pretty long compund String:

var result = string1 + " - " + string2 + " - " + string3;

and I display the String in the Website by creating a new list item:

var listElement = document.createElement("li"),
container = document.querySelector("#resultlist"); //I have a <ul id="resultlist">
listElement.appendChild(document.createTextNode(result));
container.appendChild(listElement);

How can I add a <br /> tag between e.g. the second and the third part of the String? So, I need something like this:

result = string1 + " - " + string2 + " <br /> " + string3;

(But that attempt just displays the tag).
I also tried the \n command already, but this had no effect on the website output.

Thanks for your help!

like image 534
erik4thewinners Avatar asked Oct 31 '25 12:10

erik4thewinners


1 Answers

The <br /> tag is HTML (at least you want it to be interpreted as HTML). You cannot add HTML to pages using createTextNode(), as the name suggests. You should use innerHTML instead.

var result = "First String" + " - " + "Second String" + " <br /> " + "Third String",
listElement = document.createElement("li"),
container = document.querySelector("#resultlist"); //I have a <ul id="resultlist">
listElement.innerHTML = result;
container.appendChild(listElement);
<ul id="resultlist"></ul>
like image 133
Cedric Ipkiss Avatar answered Nov 03 '25 03:11

Cedric Ipkiss



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!