How to set DOM element as the first child?

How to set DOM element as the first child?

I have element E and I’m appending some elements to it. All of a sudden, I find out that the next element should be the first child of E. What’s the trick, how to do it? Method unshift doesn’t work because E is an object, not array.
Long way would be to iterate trough E’s children and to move’em key++, but I’m sure that there is a prettier way.


Solution 1:

var eElement; // some E DOM instance
var newFirstElement; //element which should be first in E

eElement.insertBefore(newFirstElement, eElement.firstChild);

Solution 2:

2017 version

You can use

targetElement.insertAdjacentElement('afterbegin', newFirstElement)

From MDN :

The insertAdjacentElement() method inserts a given element node at a given position relative to the element it is invoked upon.

A DOMString representing the position relative to the element; must be one of the following strings:
beforebegin: Before the element itself.
afterbegin: Just inside the element, before its first child.
beforeend: Just inside the element, after its last child.
afterend: After the element itself.

The element to be inserted into the tree.

Also in the family of insertAdjacent there is the sibling methods:

Related:  mocha pass variable to the next test

element.insertAdjacentHTML('afterbegin','htmlText') for inject html string directly, like innerHTML but without overide everything , so you can jump oppressive process of document.createElement and even build whole componet with string manipulation process

element.insertAdjacentText for inject sanitize string into element . no more encode/decode

Solution 3:

2018 version


This is modern JS! It is more readable than previous options. It is currently available in Chrome, FF, and Opera.

P.S. You can directly prepend strings

parentElement.prepend('This text!');

Can I Use – 90% May 2019


Solution 4:

You can implement it directly i all your window html elements.
Like this :

    else this.appendChild(childNode);

Solution 5:

Accepted answer refactored into a function:

function prependChild(parentEle, newFirstChildEle) {
    parentEle.insertBefore(newFirstChildEle, parentEle.firstChild)

Solution 6:

Unless I have misunderstood:




Although it sounds like from your description that there is some condition attached, so

if (SomeCondition){