Categories
JavaScript Answers

How to add anchor tags dynamically to a div in JavaScript?

Spread the love

To add anchor tags dynamically to a div in JavaScript, we use the createElement method.

For instance, we write

const myDiv = document.getElementById("myDiv");
const aTag = document.createElement("a");
aTag.setAttribute("href", "yourlink.html");
aTag.innerText = "link text";
myDiv.appendChild(aTag);

to select the div with getElementById.

Then we create a link with createElement.

Next, we call setAttribute to set the value of the href attribute.

We set the innerText property to set the link text.

Finally, we add the link as the last child of the div with myDiv.appendChild.

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 *