pavan
pavan

Reputation: 451

How to add hyperlinks dynamically to a div tag in Javascript?

I want to add a hyperlink on the ribbon. I was able to add the hyperlink to the existing div. The Hyperlinks are getting increased by one for every action i do on the page. How i can make it(hyperlink) restrict to one?

I am using the following code:

var mydiv = document.getElementById("myDiv"); 
var aTag = document.createElement('a');
aTag.setAttribute('href',"yourlink.htm");
aTag.innerHTML = "link text";
mydiv.appendChild(aTag);

Please suggest me.

Upvotes: 0

Views: 5235

Answers (1)

Aesthete
Aesthete

Reputation: 18850

var aTag = document.createElement('a');

Creates a new anchor element everytime it's called. Without more context it's hard to see why and how often this code is called.

What we do know, is every time it's called, you're appending it to the div, which is why you have multiple links.

mydiv.appendChild(aTag);

Upvotes: 1

Related Questions