Mark As Completed Discussion

Removing Elements

Sometimes, we may need to remove HTML elements from the DOM. This can be done using the remove() method.

To remove an element, you first need to select it using a method such as getElementById, querySelector, or getElementsByClassName.

Once you have a reference to the element you want to remove, you can call the remove() method on it.

Here's an example that removes three elements with IDs 'element0', 'element1', and 'element2':

JAVASCRIPT
1for (let i = 0; i < 3; i++) { 
2  const elementToRemove = document.getElementById('element' + i); 
3  if (elementToRemove) { 
4    elementToRemove.remove(); 
5  } 
6}

In this example, we use a loop to remove multiple elements with different IDs.

Try removing elements from the DOM in your own project using the remove() method.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment