Let's say, I have a pretty long pund 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 mand already, but this had no effect on the website output.
Thanks for your help!
Let's say, I have a pretty long pund 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 mand already, but this had no effect on the website output.
Thanks for your help!
Share Improve this question edited May 1, 2017 at 21:52 erik4thewinners asked May 1, 2017 at 21:48 erik4thewinnerserik4thewinners 2091 gold badge4 silver badges12 bronze badges 6-
3
You're creating a text node. Try creating an element, and set its
innerHTML
property through Javascript. Also#
is for id.
is for css classes developer.mozilla/en-US/docs/Web/API/Document/createElement – Alex Szabo Commented May 1, 2017 at 21:50 -
Another thing to try is wrapping your result in a span:
result = "<span>" + string1 + " - " + string2 + " <br/> " + string3 + "</span>"
– Paul Stoner Commented May 1, 2017 at 21:53 - 3 Read what you're writing. "create Text Node". HTML is not text! – Lightness Races in Orbit Commented May 1, 2017 at 22:03
- Okay so how do I have to change the code? – erik4thewinners Commented May 1, 2017 at 22:07
-
2
Create two text nodes, one for each line. Append the first text node, then a
br
element, then the second text node. – Barmar Commented May 1, 2017 at 22:08
1 Answer
Reset to default 2The <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>