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();
    });
2
  • 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. Commented Aug 18, 2017 at 15:23
  • if (element.tagName == 'A' && element.classList.contains('download-link')) { source Commented Aug 18, 2017 at 15:26

1 Answer 1

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
        })
}
Sign up to request clarification or add additional context in comments.

4 Comments

Please edit your answer to make it more clear what the OP did wrong, and how to fix it.
@JamesDouglas The original Answer did mention what was incorrect, and provided code for how to correct the issue. Updated post for further clarity nonetheless
Thank you - however It doesn't seem to be selecting for me on this code
@TMB87 What do you mean by "doesn't seem to be selecting"? At which browser are you trying code?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.