Advertisement

Google Ad Slot: content-top

Js Add and Remove Element

~1 min read · JS
On this page

JavaScript provides powerful tools to dynamically add and remove elements in the DOM. These operations are useful for creating interactive web applications, updating UI, and managing content.


Creating Elements:

The createElement() method create a new element

Example
Try it yourself

Adding Elements:

To add elements to the DOM, you typically use the following methods:

1. Using appendChild()

Adds a new child element as the last child of a parent element.

Example
Child 1
Try it yourself

2. Using append()

Similar to appendChild(), but more versatile as it can append multiple nodes and text.

Example
Try it yourself

3. Using prepend()

Adds a new child element as the first child of a parent element.

Example
Child 1
Try it yourself

4. Using insertBefore()

Inserts a new element before an existing child of a parent element.

Example
Child 1
Child 2
Try it yourself

Removing Elements

To remove elements, you can use these methods:

1. Using removeChild()

Removes a child element from its parent.

Example
Child 1
This is a new element!
Try it yourself

2. Using remove()

Directly removes an element from the DOM.

Example
Child 1
This is a new element!
Try it yourself

3. Using replaceChild()

Replaces an existing child element with a new element.

Example
Child 1
This is a new element!
Try it yourself