Categories
JavaScript Answers

How to dynamically create HTML elements using JavaScript?

Spread the love

Sometimes, we want to dynamically create HTML elements using JavaScript

In this article, we’ll look at how to dynamically create HTML elements using JavaScript.

How to dynamically create HTML elements using JavaScript?

To dynamically create HTML elements using JavaScript, we can use the createElement method.

For instance, we write:

<div id="main"></div>

to add a container div.

Then we write:

const tree = document.createDocumentFragment();
const link = document.createElement("a");
link.setAttribute("id", "id1");
link.setAttribute("href", "http://example.com");
link.appendChild(document.createTextNode("linkText"));

tree.appendChild(link);
document.getElementById("main").appendChild(tree);

to call createElement with 'a‘ to create an anchor element.

Then we call setAttribute to set the id and href attributes.

Next, we call link.appendChild to append the text node with the link text into it.

And then we call appendChild with link and tree to append the link and tree as child of elements tree and the the div with id main respectively.

Conclusion

To dynamically create HTML elements using JavaScript, we can use the createElement 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 *