Creating and Removing Elements
JavaScript doesn't just let you change what's already on a page — it also allows you to create new elements or remove existing ones on the fly. This is super helpful when you want your website to react to user actions, like adding new comments or removing tasks from a to-do list.
createElement, appendChild
To create a new element, you use document.createElement()
, and to add it to the page, you use appendChild()
.
Example:
const newParagraph = document.createElement('p');
newParagraph.textContent = 'This is a new paragraph!';
document.body.appendChild(newParagraph);
Here, we create a new <p>
element, add some text inside it, and then attach it to the page's <body>
.
removeChild, remove()
Sometimes you need to remove elements too. There are two common ways to do this:
Using removeChild()
:
const list = document.querySelector('ul');
const item = document.querySelector('li');
list.removeChild(item);
Here, you find the parent element first (ul
), then tell it to remove one of its children (li
).
Using remove()
(simpler way):
const item = document.querySelector('li');
item.remove();
With remove()
, you directly tell the element to remove itself without needing its parent.
Setting attributes dynamically
You can also set or update an element’s attributes (like href
, src
, id
, etc.) after creating it. This is done using setAttribute()
.
Example:
const link = document.createElement('a');
link.setAttribute('href', 'https://example.com');
link.textContent = 'Visit Example';
document.body.appendChild(link);
Now you have a clickable link created entirely with JavaScript!
Using insertBefore() for better control
If you need to insert a new element at a specific spot (not just at the end), you can use insertBefore()
.
Example:
const list = document.querySelector('ul');
const newItem = document.createElement('li');
newItem.textContent = 'New Item';
const firstItem = list.firstElementChild;
list.insertBefore(newItem, firstItem);
This will insert the new list item at the top instead of the bottom.