0

I'm used to writing in jQuery for selecting by class, however the following I can't quite get the code right. This lives on every page and should just intercept links with the class 'download-link'. The following works for all links. But i want to target it just for download-link css.

 document.onclick = function (e) {
                e = e ||  window.event;
                var element = e.target || e.srcElement;

                if (element.tagName == 'A') {
                    window.open(element.href, "_blank", "location=yes,toolbar=yes,toolbarposition=top");
                    return false; 
                }

            };

I can't quite work out the selector for my if statement to change element.tagName to be element.class or similar.

Heres the last thing I tried

 document.getElementById("download-link").addEventListener("click", function(e) {
        window.open(e.href, "_blank", "location=yes,toolbar=yes,toolbarposition=top");
return false;
        e.preventDefault();
    });
matisetorm
  • 857
  • 8
  • 21
MissCoder87
  • 2,669
  • 10
  • 47
  • 82
  • 2
    `getElementById`  does not get the elements with the **class** `download-link`. it gets the element with the **id**. If you want to get the elements with a certain class, you need to use `document.getElementsByClassName`. – litelite Aug 18 '17 at 15:23
  • `if (element.tagName == 'A' && element.classList.contains('download-link')) {` [source](https://stackoverflow.com/a/35615762/7733026) – James Douglas Aug 18 '17 at 15:26

1 Answers1

4

You mention

should just intercept links with the class 'download-link'

though use .getElementById(). You can use .querySelectorAll() with selector ".download-link" and NodeList.prototype.forEach() to perform a task, see forEach method of Node.childNodes?. For example, attach an event listener, to each ".download-link" element

document.querySelectorAll(".download-link")
.forEach(function(element) {
  element.addEventListener("click", function(event) {
  // do stuff
  })
})

If NodeList.prototype.forEach() is not defined at browser you can use for loop to achieve same result

for (var i = 0, nodes = document.querySelectorAll(".download-link");
      nodes && i < nodes.length; i++) {
        nodes[i].addEventListener("click", function(event) {
        // do stuff
        })
}
guest271314
  • 1
  • 15
  • 104
  • 177