Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 332
Yuki Watayu Avatar asked Feb 08 '18 16:02

Yuki Watayu


1 Answers

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.

like image 50
Scott Marcus Avatar answered Oct 21 '22 14:10

Scott Marcus