Blog

Thoughts from my daily grind

Remove an HTML element from the DOM structure - No jQuery

Posted by Ziyan Junaideen |Published: 04 May 2021 |Category: JavaScript
Default Upload |

In the previous article, I discussed how you could add an HTML element to the dom structure. It describes how you can append, prepend, insert before, insert after and replace. This article will look at removing HTML elements from the DOM structure using nothing but vanilla JavaScript.

Element Identification

Before we remove an element, we require to identify it. Let's use the query selector to find the element we want to remove.

var element;
element = document.querySelector('#element-to-remove');

Remove from View

When we are going to remove an element, we have to decide if we will remove an element from the dom structure (in other words, delete it) or if we are going to hide it from being visible with the intent of showing it later.

Hide the element - for later use

If you want to hide an element, we can use the display none CSS property. If you are on Bootstrap, you can use the d-none CSS class. In case your framework is Zurb Foundation, you can use the hidden CSS class. Hiding is useful if we intend to make the element visible again.

// adding inline CSS property
element.style.display = 'none';

// if you are using Bootstrap, you can use the d-none HTML class
element.classList.add('d-none');

Remove it from the DOM structure

If you do not have any further use of the element during the page's lifecycle, you may remove it. You will have to obtain the elements parent node and notify that node to remove its child.

element.parentNode.removeChild(element);

Conclusion

This blog post discussed how we could identify a node. Then we looked into either hiding or removing it from the DOM structure entirely using nothing but vanilla JavaScript. This is the second post of my "No jQuery" series of blog posts. I hope it was helpful. If you have any question, remember, you can always StackOverflow it 🤭. I am just messing with you; leave a comment below.

Tags
About the Author

Ziyan Junaideen -

Ziyan is an expert Ruby on Rails web developer with 8 years of experience specializing in SaaS applications. He spends his free time he writes blogs, drawing on his iPad, shoots photos.

Comments