How to set DOM element as the first child?

JavascriptJqueryArraysDomElements

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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

eElement.insertBefore(newFirstElement, eElement.firstChild);

Solution 2 - Javascript

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

  1. You can pass multiple values (or use spread operator ...).
  2. 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"]
  1. Read More - child.before and child.after
  2. Read More - child.replaceWith

Mozilla Documentation

Can I Use

Solution 3 - Javascript

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.

In the family of insertAdjacent there is the sibling methods:

element.insertAdjacentHTML('afterbegin','htmlText')`

That can inject html string directly, like innerHTML but without override everything, so you can use it as a mini-template Engin and jump the oppressive process of document.createElement and even build a whole component with string manipulation process

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

Solution 4 - Javascript

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

HTMLElement.prototype.appendFirst = function(childNode) {
	if (this.firstChild) {
        this.insertBefore(childNode, this.firstChild);
    }
    else {
        this.appendChild(childNode);
    }
};

Solution 5 - Javascript

Accepted answer refactored into a function:

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

Solution 6 - Javascript

Unless I have misunderstood:

$("e").prepend("<yourelem>Text</yourelem>");

Or

$("<yourelem>Text</yourelem>").prependTo("e");

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

if (SomeCondition){
    $("e").prepend("<yourelem>Text</yourelem>");
}
else{
    $("e").append("<yourelem>Text</yourelem>");
}

Solution 7 - Javascript

I think you're looking for the .prepend function in jQuery. Example code:

$("#E").prepend("<p>Code goes here, yo!</p>");

Solution 8 - Javascript

I created this prototype to prepend elements to parent element.

Node.prototype.prependChild = function (child: Node) {
    this.insertBefore(child, this.firstChild);
    return this;
};

Solution 9 - Javascript

var newItem = document.createElement("LI");       // Create a <li> node
var textnode = document.createTextNode("Water");  // Create a text node
newItem.appendChild(textnode);                    // Append the text to <li>

var list = document.getElementById("myList");    // Get the <ul> element to insert a new node
list.insertBefore(newItem, list.childNodes[0]);  // Insert <li> before the first child of <ul>

https://www.w3schools.com/jsref/met_node_insertbefore.asp

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPoparaView Question on Stackoverflow
Solution 1 - JavascriptnemisjView Answer on Stackoverflow
Solution 2 - JavascriptGiboltView Answer on Stackoverflow
Solution 3 - Javascriptpery mimonView Answer on Stackoverflow
Solution 4 - JavascriptyorgView Answer on Stackoverflow
Solution 5 - JavascriptJoseph DykstraView Answer on Stackoverflow
Solution 6 - JavascriptJames WisemanView Answer on Stackoverflow
Solution 7 - JavascriptEmil VikströmView Answer on Stackoverflow
Solution 8 - JavascriptRazaView Answer on Stackoverflow
Solution 9 - JavascriptIlker CatView Answer on Stackoverflow