HTML DOM Element insertBefore() na method

Paglilinaw at paggamit

insertBefore() Ang method ay nagdaragdag ng anak sa bago sa kasalukuyang mga anak.

Mga nagbabagay:

appendChild() na method

replaceChild() na method

removeChild() na method

remove() na method

childNodes na attribute

firstChild na attribute

lastChild na attribute

firstElementChild na attribute

lastElementChild na attribute

Eksemplo

Halimbawa 1

  1. Lumikha ng elemento <li>
  2. Lumikha ng tekston na node
  3. Idagdag ang teksto sa elemento <li>
  4. Sa unang anak ng <ul> ay iinsert ang elemento <li>;
const newNode = document.createElement("li");
const textNode = document.createTextNode("Water");
newNode.appendChild(textNode);
const list = document.getElementById("myList");
list.insertBefore(newNode, list.children[0]);

Try It Yourself

Example 2

Move the last element from one list to the beginning of another list:

const node = document.getElementById("myList2").lastElementChild;
const list = document.getElementById("myList1");
list.insertBefore(node, list.children[0]);

Try It Yourself

Example 3

Move the last element from one list to the end of another list:

const node = document.getElementById("myList2").lastElementChild;
const list = document.getElementById("myList1");
list.insertBefore(node, null);

Try It Yourself

Syntax

element.insertBefore(newnode, existingnode)

or

node.insertBefore(newnode, existingnode)

Parameter

Parameter Description
newnode Required. The node to be inserted (element).
existingnode

Optional. Insert a new node's child node before it.

If not specified, the insertBefore method will insert newnode at the end.

Return Value

Type Description
Node The node to be inserted.

Browser Support

element.insertBefore() It is a DOM Level 1 (1998) feature.

All browsers fully support it:

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Support 9-11 Support Support Support Support