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 - Adding DOM Elements

Use appendChild to add the new element under its parent.

This is a paragraph.

This is another paragraph.


<div id="div1">
    <p id="p1">This is a paragraph.</p>
    <p id="p2">This is another paragraph.</p>
</div>

let newParagraph = document.createElement("p");
let paragraphText = document.createTextNode("This is new.");
newParagraph.appendChild(paragraphText);
newParagraph.setAttribute("class","text-success");
// or
// newParagraph.innerHTML = "This is new";
var element = document.getElementById("div1");
element.appendChild(newParagraph);