JQuery Check If Target Is Link
I have a global function to capture clicks. $(document).click(function(e){ //do something if(clickedOnLink) //do something }); I want to do additional stuff when the targe
Solution 1:
You can try to see if the element you clicked on either is or is a child of an <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');
}
});
Solution 2:
I believe using is
will actually have better performance than the answers suggesting closest
:
$(e.target).is('a, a *');
This checks if the element itself is an a
or if it is contained with an a
.
This should be faster than closest
because it will use matches on the element itself and not need to traverse up the DOM tree as closest
will do.
Solution 3:
Try this
$(document).click(function(e){
//do something
if($(this).closest('a').length)
//do something
});
Solution 4:
If the exact target is link, then you can use .is()
Example:
$(".element").on("click", function(e){
if($(e.target).is("a")){
//do your stuff
}
});
EDIT:
If it is surrounded by other element that is inside an anchor tag, then you can use closest()
and check whether it have anchor tag parent or not by using length
Example:
$(".element").on("click", function(e){
if($(e.target).closest("a").length){
//do your stuff
}
});
Solution 5:
With jquery just get the tagName attribute $("a").prop("tagName");
Post a Comment for "JQuery Check If Target Is Link"