How to add and remove HTML elements using JavaScript

How to add and remove HTML elements using JavaScript

In JavaScript, you can dynamically add or remove HTML elements from the DOM (Document Object Model) using various methods. Here are some examples:

1) Adding elements:

a) createElement() and appendChild():

To add a new element to the DOM, you can create it using the createElement() method and then add it to the document using the appendChild() method. For example, the following code creates a new div element and adds it to the end of the body element:

b) insertAdjacentHTML():

Alternatively, you can use the insertAdjacentHTML() method to insert HTML code directly into the DOM. This method takes two arguments: the position where the new HTML should be inserted (beforebegin, afterbegin, beforeend, or afterend), and the HTML code to be inserted. For example, the following code adds a new div element before the end of the body element:

2) Removing elements:

a) removeChild():

To remove an element from the DOM, you can use the removeChild() method of the parent element. For example, the following code removes the first div element from the body:

b) remove():

Alternatively, you can use the remove() method of the element itself to remove it from the DOM. For example, the following code removes the second div element from the body:

These are just some of the methods available for adding and removing HTML elements using JavaScript. The specific method you choose will depend on your specific use case and the structure of your HTML document.

Thanks for reading and learning ❤️

#LetsCodeIt