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 DO
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.