Javascript attach an onclick event to all links

I want to attach a function on every link on the site to change a parameter.

How can I do this without jQuery?

How do I traverse every link (it might be a DOM item) and call a function on them?

Answers:

Answer

getElementsByTagName is supported by all modern browsers and all the way back to IE 6

var elements = document.getElementsByTagName('a');
for(var i = 0, len = elements.length; i < len; i++) {
    elements[i].onclick = function () {
        // stuff
    }
}
Answer

It's weird that nobody offered an alternative solution that uses event bubbling

function callback(e) {
    var e = window.e || e;

    if (e.target.tagName !== 'A')
        return;

    // Do something
}

if (document.addEventListener)
    document.addEventListener('click', callback, false);
else
    document.attachEvent('onclick', callback);

The pros of this solution is that when you dynamically add another anchor, you don't need to specifically bind an event to it, so all links will always fire this, even if they were added after these lines were executed. This is in contrast to all the other solutions posted so far. This solution is also more optimal when you have a large number of links on your page.

Answer
function linkClickHandler(a) {
  console.log(a.host);
}

var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) links[i].onclick = function() {
    linkClickHandler(links[i]);
}
Answer

better way:

const item = document.querySelectorAll(".nav__item");

item.forEach(link => {
  link.addEventListener("click", function () {
    link.classList.add("nav__item--active");
  });
});
Answer

Something like this should be useful for you:

var elements = document.getElementsByTagName("a"),
    i,
    len,
    el;

for (i = 0, len = elements.length; i < len; i++) {
    el = elements[i];

    // Do what you need on the element 'el'
}
Answer

Try using getElementsByTagName('a')

Answer

I wanted to offer an improvement on @zatatatata's answer which also works with links with nested elements.

function findLink(el) {
    if (el.tagName == 'A' && el.href) {
        return el.href;
    } else if (el.parentElement) {
        return findLink(el.parentElement);
    } else {
        return null;
    }
};

function callback(e) {
    const link = findLink(e.target);
    if (link == null) { return; }
    e.preventDefault();
    // Do something here
};

document.addEventListener('click', callback, false);

If the clicked element isn't a link, we search its parents to check for a link element.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.