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?
This is a type of JavaScript link - the onclick attribute defines a JavaScript action when the 'onclick' event for the link is triggered (i.e. when a user clicks the link) - and there is a URL present itself in the onclick attribute.
To add the event listener to the multiple elements, first we need to access the multiple elements with the same class name or id using document. querySelectorAll() method then we need to loop through each element using the forEach() method and add an event listener to it.
The other way can be using document. getElementsByTagName('a') you can get reference to all the href's as array then you can chose that particular href and add click event to it.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With