HTML
var x = document.createElement("p");
var br1 = document.createElement('br');
var br2 = document.createElement('br');
var t5 = document.createTextNode("CSE");
var t6 = document.createTextNode("EEE");
x.appendChild(t5);
x.appendChild(br1);
x.appendChild(t6);
x.appendChild(br2);
document.getElementById("new").appendChild(x);
The output should look like
CSE
EEE
but now the output is CSEEEE
HTML
var x = document.createElement("p");
var br1 = document.createElement('br');
var br2 = document.createElement('br');
var t5 = document.createTextNode("CSE");
var t6 = document.createTextNode("EEE");
x.appendChild(t5);
x.appendChild(br1);
x.appendChild(t6);
x.appendChild(br2);
document.getElementById("new").appendChild(x);
The output should look like
CSE
EEE
but now the output is CSEEEE
- Possible duplicate of How to insert a line break with javascript? – ConnorCMcKee Commented Jun 15, 2016 at 20:21
- 1 Answer to a similar question: "If you call appendChild passing in an element that's already in the DOM, it's moved, not copied." (How to add multiple divs with appendChild?) – user2314737 Commented Jun 15, 2016 at 20:32
3 Answers
Reset to default 4The issue here is with the br
element you created. It is unique. So at first when you append it to its place in the DOM, it sits in between the t5 and t6 element. However, when you append the br element a second time, it places it in a different location in the DOM and that is why you see the result of CSEEEE followed by only 1 br element.
You should either omit the last one, or clone the br element.
var x = document.createElement("p");
var br = document.createElement('br');
var t5=document.createTextNode("CSE");
var t6=document.createTextNode("EEE");
x.appendChild(t5);
x.appendChild(br);
x.appendChild(t6);
x.appendChild(br.cloneNode());
document.getElementById("new").appendChild(x);
<div id="new">
you can't reuse the same elemnt
var x = document.createElement("p");
var t5=document.createTextNode("CSE");
var t6=document.createTextNode("EEE");
x.appendChild(t5);
x.appendChild(document.createElement('br'));
x.appendChild(t6);
x.appendChild(document.createElement('br'));
document.getElementById("new").appendChild(x);
You have to create two <br>
var x = document.createElement("p");
var br1 = document.createElement('br');
var br2 = document.createElement('br');
var t5 = document.createTextNode("CSE");
var t6 = document.createTextNode("EEE");
x.appendChild(t5);
x.appendChild(br1);
x.appendChild(t6);
x.appendChild(br2);
document.getElementById("new").appendChild(x);