Categories
JavaScript Answers

How to add an element to the DOM with JavaScript?

Spread the love

Sometimes, we want to add an element to the DOM with JavaScript.

In this article, we’ll look at how to add an element to the DOM with JavaScript.

How to add an element to the DOM with JavaScript?

To add an element to the DOM with JavaScript, we can use the appendChild method.

For instance, we write:

const newDiv = document.createElement("div");
newDiv.appendChild(document.createTextNode("some text"));
document.body.appendChild(newDiv);

to create a new div with createElement.

Then we call createTextNode to create a new text node.

And then we append the text node as the child of the div with newDiv.appendChild.

Finally, we append the div as a child of the body element with document.body.appendChild.

Conclusion

To add an element to the DOM with JavaScript, we can use the appendChild method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *