Chad Chad - 27 days ago 7
jQuery Question

Add click handler on all A tags using jQuery

Trying to add a click event handler on all A tags using jQuery. Tried with and without the document.ready, also used document.getElementsByTagName("a"); without luck. It's logging 'document is ready' but doesn't attach the event listeners. Thank you for the help!

$( document ).ready(function() {
console.log('document is ready');
$('a').each(function(){
$(this).addEventListener("click",
function (event) {
console.log(event);
event.preventDefault();
}, false
);
});
});

Lix Lix
Answer

Using jquery selectors you don't actually need to manually attach a click handler to each element - rather you can attach the handler to any element that matches the selector.

$('a') will match any <a> tag on the page, so it should be enough for you in this case.

$( document ).ready(function() {
   console.log('document is ready');
    $('a').click(function( event ){
      console.log(event);
    });
});

Within your click handler, the this context will be set to the element that was actually clicked.

    $('a').click(function( event ){
      // "this" is the <a> that triggered the event.
      // "$(this)" is the same element in a jquery wrapper.
    });
Comments