Animations

API

Arrays

Async

Basics

Challenges

Classes

Console

Dates

Debugging

DOM Elements

DOM Methods

DOM Navigation

DOM Properties

Event Listeners

Flow Control

Forms

Functions

Global Functions

JSON

Keywords

Libraries (3rd party)

Math

Modules

Objects

Snippets

String

Types

Widgets

Window Object

JavaScript - Create New Nodes

To add a new element to the HTML DOM, you must create the element (element node) first, and then append it to an existing element. To do this, you need to use the createElement and createTextNode methods.


This is a paragraph.

This is another paragraph.



    let para = document.createElement("p");
    let node = document.createTextNode("This paragraph was created and inserted via javascript.");
    para.setAttribute("class","text-danger");
    para.appendChild(node);

    let element = document.getElementById("div1");
    element.appendChild(para);


Notice that this appended the paragraph element. If you want to insert the new element (node) before everything else, refer to the example below.

insertBefore()
insertBefore() takes two arguments. The element to be inserted and the element to insert it in front of.


This is a paragraph.

This is another paragraph.


let para2 = document.createElement("p");
let node2 = document.createTextNode("This paragraph was created and inserted via javascript.");
para2.setAttribute("class", "text-danger");
para2.appendChild(node2);

let element2 = document.getElementById("div2");
let child2 = document.getElementById("p3");
element2.insertBefore(para2, child2);