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
.