Yuki Watayu
Yuki Watayu

Reputation: 93

setAttribute download for anchor tag using JavaScript

I want to use Javascript to make an anchor tag inside a button, so that, when I click this button, it will download a specified file I set before. But I don't know how to add attribute "download" when using Javascript create it.

function myFunction() {
    var mydiv = document.getElementById("myDiv");
    var aTag = document.createElement('a');
    aTag.setAttribute('href',"abc.com/example.exe");
    aTag.innerHTML = "<button>GO</button>";
    mydiv.appendChild(aTag);
}

Upvotes: 9

Views: 19429

Answers (1)

Scott Marcus
Scott Marcus

Reputation: 65806

download is a Boolean attribute. That is, in HTML, no value is required to use it. The mere presence of the attribute is enough to make it work. Because of this, any value you might place on it isn't going to affect it working or not.

So, in situations like this, where you need to come up with a value for it, the recommendation is to use the attribute name as the value, so your code would be:

aTag.setAttribute('download',"download");

Other examples of Boolean attributes are: disabled and readonly.

Upvotes: 13

Related Questions