1

How i can make this code works

<a href="downloadFile.zip" class="button">Download the file...</a>

with

    var downloadButton = document.getElementsByClassName("button");
var counter = 10;
var newElement = document.createElement("p");
newElement.innerHTML = "You can download the file in 10 seconds.";
var id;

downloadButton.parentNode.replaceChild(newElement, downloadButton);

id = setInterval(function() {
    counter--;
    if(counter < 0) {
        newElement.parentNode.replaceChild(downloadButton, newElement);
        clearInterval(id);
    } else {
        newElement.innerHTML = "You can download the file in " + counter.toString() + " seconds.";
    }
}, 1000);

I don't want to add id="download"

Please help me. anyone can help me? Please i need your help. Thanks

1 Answers1

2

The key difference between getElementById() and getElementsByClassName() is that the latter returns an array, therefore you need to either loop through all elements returned or access the specific one you want by index.

As you only appear to require the first .button element, you can just do:

var downloadButton = document.getElementsByClassName("button")[0]; // note the [0]

var downloadButton = document.getElementsByClassName("button")[0];
var counter = 10;
var newElement = document.createElement("p");
newElement.innerHTML = "You can download the file in 10 seconds.";
var id;

downloadButton.parentNode.replaceChild(newElement, downloadButton);

id = setInterval(function() {
  counter--;
  if (counter < 0) {
    newElement.parentNode.replaceChild(downloadButton, newElement);
    clearInterval(id);
  } else {
    newElement.innerHTML = "You can download the file in " + counter.toString() + " seconds.";
  }
}, 1000);
<a href="downloadFile.zip" class="button">Download the file...</a>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339