How can I check if the clicked element was an anchor containing an img?
So for example I want to check if this element was clicked:
<a href="#">
<img src="#" />
<a/>
jQuery(document).click(function(e) {
// e.target.hereIsWhereINeedHelp;
});
Thanks in advance!
How can I check if the clicked element was an anchor containing an img?
So for example I want to check if this element was clicked:
<a href="#">
<img src="#" />
<a/>
jQuery(document).click(function(e) {
// e.target.hereIsWhereINeedHelp;
});
Thanks in advance!
Share Improve this question edited Apr 15, 2015 at 15:58 Rory McCrossan 338k41 gold badges320 silver badges351 bronze badges asked Apr 15, 2015 at 15:53 user1878980user1878980 5212 gold badges8 silver badges22 bronze badges6 Answers
Reset to default 8If you wish to capture the "click" from any element:
jQuery(document).click(function(e) {
if (jQuery(e.target).is('a') && jQuery(e.target).has('img')) {
// code goes here
}
});
Whether you choose to prevent the "default behavior" is another question.
You can use .is("a")
and .has("img")
:
<a href="#">
<img src="#" />
<a/>
<script>
jQuery(document).click(function(e) {
var target = $( e.target );
if ( target.is( "a" ) && target.has("img") ) {
//Do what you want to do
}
});
</script>
You can use the has()
method to check if an element contains another:
$('a').click(function(e) {
e.preventDefault(); // this will stop the link from going anywhere.
if ($(this).has('img')) {
// do something
}
});
You could also use if ($(this).find('img').length)
.
Use has()
method
this.has("img");
You can use has()
or find()
$("a").on("click", function(e) {
e.preventDefault(); // Prevents the link redirection
if ( $(this).has("img") ) {
console.log("has image");
}
});
Just check if the clicked element is an anchor tag using is
, and then use find
to look for an image
. If both are true then you //do something
.
jQuery(document).click(function() {
var el = $(this);
if(el.is("a") && el.find("img").length > 0){
//do something
}
});