Creating & Removing Elements

In JavaScript, you can dynamically create and remove HTML elements to update the content of your webpage without reloading it.

Creating Elements

Use document.createElement() to create a new element. Then, set its properties or content, and insert it into the DOM using methods like appendChild() or insertBefore().

📌 Deep Dive: Create and Append an Element

JAVASCRIPT
const newParagraph = document.createElement('p');
newParagraph.textContent = 'This is a new paragraph.';
document.body.appendChild(newParagraph);
Output
New paragraph added to the end of the document body.

Removing Elements

To remove an element, use remove() directly on the element, or use parentNode.removeChild(child) from its parent.

📌 Deep Dive: Remove an Element

JAVASCRIPT
const element = document.querySelector('p');
element.remove();
Output
The first <p> element is removed from the DOM.
Illustration of creating_removing_elements
Illustration of creating_removing_elements

💡 Remember:

Always ensure the element exists before removing it to avoid errors.

Creating vs Removing Elements
ActionMethod
Create elementdocument.createElement(tagName)
Add elementparent.appendChild(element)
Remove elementelement.remove() or parent.removeChild(element)

⚠️ Important:

Modifying the DOM frequently can affect performance. Batch your changes or use DocumentFragments for many elements.