05. Creating and Deleting Elements

We've looked at how to access the current elements on the DOM, so now let's learn how to create and delete them.

Creating Elements

To create an element, use the createElement() method, which takes in an element type. We then store this reference into a variable, and use the methods we learned in the previous lessons to add attributes and text nodes.

var newElement = document.createElement("p");
body.appendChild(newElement);
body.newElement.removeChild(newElement);

You have now created your first element from JavaScript! Now let's add it to the DOM so it renders on the page.

Setting attributes

To set attributes to our newly created element Now we can just set the ID.

newElement.setAttribute("class", "body-text")

Creating a text node

We may also create a text node by using the createTextNode() method. Simply attach this node to our element.

var myTextNode = document.createTextNode("text here");
newElement.appendChild(myTextNode);

Adding the element to the DOM

To append the element to the DOM, we use the appendChild() method. This takes in the variable that holds a reference to your newly created element. You can then attach it to any pre-exiting element.

Deleting elements

To remove a node, simply use the removeChild() method.

var elementRemoval = document.getElementById("removeMe");
document.body.removeChild(elementRemoval);

Build modern and responsive webpages

Responsive Typography

Build modern and responsive webpages Try Front-end

Responsive web design helps your site maintain its design integrity on a variety of screen sizes, but how does it affect your typography? With this practical book, graphic designers, web designers, and front-end developers alike will learn the nuts and bolts of how to get the best appearance from type without sacrificing performance on any device.

$ Check price
24.9924.99Amazon 4.5 logo(3+ reviews)

More Front-end resources

Aching back from coding all day?

Inversion Therapy Table

Aching back from coding all day? Try Back Problems

Stretch out your back and relieve your back muscles with inversion therapy. This device counteracts the forces of gravity on the body by decompressing and elongating the spine. By using this product just ten minutes a day, you can be well on your way to improved circulation and posture while relieving muscle aches, back pain and stress.

$$ Check price
119.98119.98Amazon 4.5 logo(1,700+ reviews)

More Back Problems resources

Ad