JavaScript basics: How to add and remove elements with Vanilla JavaScript

In the previous videos and blogs, I showed you a couple of things with getting 1 or more HTML elements via Vanilla JavaScript. This time we are going to add and remove HTML elements to our page with Vanilla JavaScript. We are gonna use the createElement, createTextNode, appendChild & removeChild methods for it.

If your not a video person, please scroll down for the written version 😉

Add element to body

First, let’s add an HTML element to our page via Vanilla JavaScript.

You create an element with the method createElement. Then create a text inside of it with the methodcreateTextNode.

Combine them with the method appendChild. After that, use the same method to add the div to the body.

Check the example code below!

HTML

JavaScript

If you want to see this code working, please check the JS Bin on jsbin.com

Add element to parent div

If you want to add a new element to an already existing element than you have to target that element instead of the body.

Check the example code below!

JavaScript

If you want to see this code working, please check the JS Bin on jsbin.com

Remove element

We also want to remove some HTML elements from our page.

It works very simple. Just target a parent element or the body, then use the methodremoveChild to remove your HTML element.

Check the example code below!

HTML

JavaScript

If you want to see this code working, please check the JS Bin on jsbin.com

Do you need help?

My question for you to answer in the comments, how did you created new elements or removed HTML elements from your page in Vanilla JavaScript? Share it with me! And if you need any help, please let me know 😊

Written by

I write stories about Frontend Dev, JavaScript, Typescript, Angular, NodeJS, Serverless Functions, JAM Stack, FaunaDB, Netlify, Apple, iOS— https://byrayray.dev

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store