Reputation: 111
I am trying to determine whether a DIV has a image or not. Structure of my DIV is as:
<li class="customData">
<div class="customdata1"><img src="" /></div>
<div class="customdata1"><input type="text" /></div>
</li>
Upvotes: 11
Views: 26230
Reputation: 337743
Try this:
$('.customData div').each(function() {
if ($(this).find('img').length) {
// there is an image in this div, do something...
}
});
This will find an img
at any level under the div
. If you only want it as a direct descendant, use this for the if
condition:
$(this).children('img').length
Upvotes: 18
Reputation: 108
HTML
<img src="some-url" class="banner-image">
Javascript way
console.log(document.querySelector('.banner-image').tagName);
jQuery way:
console.log(jQuery('.banner-image')[0].tagName);
Adding [0] - JQuery element converts to Javascript Dom object. If you are having loop then [0] is not required.
I've just found this while working and it is compatible with any browser.
Upvotes: 0
Reputation: 2230
If I understand correctly, you want to check if it has an image or not, so another way to do this I would say you need to check the src attribute, what happens if you have a img tag but no src? Which happens sometimes in dynamic environments (with actual programming code rather than plain HTML).
$('.customData .customdata1').find('img').attr('src');
Upvotes: 0
Reputation: 392
First things first lets designate the div
var dD = getElementById("desiredDivID");
now lets find child elements of the div:
var elements = dD.childNodes.length;
Now we loop through every element node:
for(index = 0; index < elements; index++){
node = dD.childNodes[index];
if (node && node.nodeType == 1 && node.nodeName == 'IMG'){
dD.removeChild(node);
}
}
in the last if statement we check for the node to exist and than check for a node type and node name. each of theese checks must return true and then .removeChild(node) removes the designated element node, which is marked in 'IMG' string.
Upvotes: 1
Reputation: 1
Maybe this will help
if ($(".customData:contains('img')")) {
console.log("sucess");
}
Upvotes: 0
Reputation: 171698
You can use the has()
selector
$('.customData div:has(img)').doSomething()
Not sure what you want to do, if you wanted to count them for example:
alert( $('.customData div:has(img)').length)
API Refrence http://api.jquery.com/has-selector/
Upvotes: 11