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");

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");

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");

Build modern and responsive webpages

The Modern Web

Build modern and responsive webpages Try Front-end

The Modern Web will guide you through the most important tools of device-agnostic web development, including HTML5, CSS3, and JavaScript. The plain-english explanations and practical examples emphasize the techniques, principles, and practices that you'll need to easily transcend individual browser quirks and stay relevant as these technologies are updated.

$ Check price
34.9534.95Amazon 4.5 logo(30+ reviews)

More Front-end resources

Aching back from coding all day?

Self-Massage Tool

Aching back from coding all day? Try Back Problems

Relieve spasms, tight muscles, trigger points and pressure points with the Body Back Buddy! This trigger point massage is designed to help you self-message any area of your body - especially those that are hard to reach. Keeping your muscles relaxes and out of contraction is importan in helping to reduce pain and prevent muscle injury.

$ Check price
29.9529.95Amazon 4.5 logo(3,443+ reviews)

More Back Problems resources