I have a global function to capture clicks.
$(document).click(function(e){
//do something
if(clickedOnLink)
//do something
});
I want t
You can test if there's a <div>
under <a>
by testing if the .children() <div>
has anything inside it. If nothing is inside, or there is no <div>
, the if
statement 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
}
});
Try this
$(document).click(function(e){
//do something
if($(this).closest('a').length)
//do something
});
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
}
});
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');
}
});
With jquery just get the tagName attribute $("a").prop("tagName");
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.