insertBefore() method: The insertBefore() method in HTML DOM is used to insert a new node before the existing node as specified by the user.
node.insertBefore( newnode, existingnode )
Parameters: This method accept two parameters as mentioned above and described below:
- newnode: It is the required parameter. This parameter contains the new node object which needs to insert.
- existingnode: It is the required parameter. It describes the position where new node insert before this node. If it set to null then insertBefore method will insert the new node at the end.
Example: In this example, the list elements are selected and then passed to a function for sorting. After sorting they are appended to the Parent element using insertBefore() method in a sorted manner.
- Before clicking on the button:
- After clicking on the button: