I'm trying to add some text and a linebreak with the code below. The Text Node t
is supposed to to have a linebreak between "myinput" and "ddd", but it doesn't work :(
Any ideas?
// Create a new list item when clicking on the "Add" button
function newElement() {
var li = document.createElement("li");
var inputText = document.getElementById("myInput").value + document.createElement("br") + "ddd" ;
var t = document.createTextNode(inputText); // this text node is supposed to have a linebreak
li.appendChild(t);
li.value = document.getElementById("myValue").value;
if (inputText === '') {
alert("You must write something!");
} else {
updateLI(li);
document.getElementById("myUL").appendChild(li);
}
document.getElementById("myInput").value = "";
document.getElementById("myValue").value = "";
}
The main issue here is a Text Node can't contain any other elements and you're trying to add a br
element into it. What you need is:
function newElement() {
var li = document.createElement("li");
var inputText = document.getElementById("myInput").value;
li.appendChild(document.createTextNode(inputText));
li.appendChild(document.createElement("br"));
li.appendChild(document.createTextNode("ddd"));
...
Keep in mind that adding \n
character to the Text Node won't help either because html "converts" all white-space to single space symbol - that is unless you use white-space: pre;
CSS applied to your element (which is another option to solve your issue).