Search code examples
javascripthtmlappendchild

<br> not being appended to div


ogres = document.getElementById('${contentID}')

.

let prettify = streamArray[streamArray.length - 1].split(/--/),
                                    layers = document.createTextNode(prettify[0]),
                                    onions = document.createTextNode(prettify[1]),
                                    breaking = document.createElement('br');

I have an array of two elements that I've created called prettify.

I have definitely confirmed that the prettify[0] and prettify[1] are the elements I want so I make them into onions and layers which are text nodes to be appended to the div.

You'll note I also have breaking which is a break element I create and also append to the div.

I then have the div, orges.

Now for some unknown reason when I do this:

ogres.appendChild(layers);
ogres.appendChild(breaking);
ogres.appendChild(onions);
ogres.appendChild(breaking);

on the html page, this is created:

layersonions
<br>

1: why is this happening

2: how do I fix it?

3: no I don't plan on keeping these variable names, but they are fun :3


Solution

  • When you use document.createElement('br'); to create an element, it is appended as the second node of the parent.

    Since you are using the same reference again, it simply detaches the existing element and appends it again in the new position.

    It is a single reference to the element. To fix it you will have to create and append an element on the fly.

    ogres.appendChild(layers);
    ogres.appendChild(document.createElement('br'));
    ogres.appendChild(onions);
    ogres.appendChild(document.createElement('br'));
    

    appendChild

    If you still want to use the variable reference then you could use the cloneNode method which will clone the existing node before insertion.

    ogres.appendChild(layers);
    ogres.appendChild(breaking);
    ogres.appendChild(onions);
    ogres.appendChild(breaking.cloneNode(false));
    

    cloneNode