How to set DOM element as the first child?
var eElement; // some E DOM instance
var newFirstElement; //element which should be first in E
eElement.insertBefore(newFirstElement, eElement.firstChild);
2018 version - prepend
parent.prepend(newChild) // [newChild, child1, child2]
This is modern JS! It is more readable than previous options. It is currently available in Chrome, FF, and Opera.
The equivalent for adding to the end is append
, replacing the old appendChild
parent.append(newChild) // [child1, child2, newChild]
Advanced usage
- You can pass multiple values (or use spread operator
...
). - Any string value will be added as a text element.
Examples:
parent.prepend(newChild, "foo") // [newChild, "foo", child1, child2]
const list = ["bar", newChild]
parent.append(...list, "fizz") // [child1, child2, "bar", newChild, "fizz"]
Related DOM methods
- Read More -
child.before
andchild.after
- Read More -
child.replaceWith
Mozilla Documentation
Can I Use
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.
position
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.element
The element to be inserted into the tree.
Also in the family of insertAdjacent
there is the sibling methods:
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