JQuery check if target is a link

I have a global function for capturing clicks.

$(document).click(function(e){ //do something if(clickedOnLink) //do something }); 

I want to do extra things when the target is a link, but if the <a> tag actually surrounds the div (as HTML5 allows), the goal is that div.

http://jsfiddle.net/Af37v/

+7
source share
7 answers

You can try to see if the element you clicked on was or is a child of the <a> tag.

 $(document).click(function(e){ if($(e.target).closest('a').length){ alert('You clicked a link'); } else{ alert('You did not click a link'); } }); 
+26
source

I believe that using is will have better performance than answers offering closest :

 $(e.target).is('a, a *'); 

This checks if the element itself is a , or if it is contained in a .

This should be faster than closest , because it will use matches for the element itself and should not go through the DOM tree as closest will be executed.

+10
source

try it

 $(document).click(function(e){ //do something if($(this).closest('a').length) //do something }); 
+5
source

With jquery, just get the tagName attribute $ ("A") prop ("tag") ;.

+1
source

Updated: You can check if the target is a or if the parent is a.

 $(function () { $(document).on('click', function (e) { $target = $(e.target); if ($target.closest('a').length > 0) { alert('i am an a'); } }); }); 

http://jsfiddle.net/8jeGV/4/

0
source

You can check if there is a <div> in the <a> by testing if the .children() <div> is inside. If nothing is inside or not a <div> , the if will return false .

I suggest this code:

 $(document).click(function(e){ var willRedirect = ($('a[href="/"]').attr('href').indexOf('#') == -1 ? true : false), //run code if ( willRedirect === false ){ e.preventDefault(); //the link will not redirect if ( $(this).children('div').html() ){ //there is a <div> inside <a> containing something } else { //there is no <div> inside <a> } } else { //the link is not pointing to your site } }); 
0
source

If the target is a link, you can use .is()

Example:

 $(".element").on("click", function(e){ if($(e.target).is("a")){ //do your stuff } }); 

EDIT:

If it is surrounded by another element inside the anchor tag, you can use closest() and check if it has a parent anchor character or not using length

Example:

 $(".element").on("click", function(e){ if($(e.target).closest("a").length){ //do your stuff } }); 
0
source

All Articles