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>
$(this). find('> img'). length could also be written as $(this). children('img').
Answer: Use the jQuery . length Propertylength property to determine whether an element exists or not in case if you want to fire some event only if a particular element exists in DOM. Here's an example that displays an alert on button click if the specified element exists.
To check if a div element contains specific text:Use the includes() method to check if the specific text is contained in the div . If it is, the includes() method returns true , otherwise false is returned.
In jQuery, you can use the . length property to check if an element exists. if the element exists, the length property will return the total number of the matched elements. To check if an element which has an id of “div1” exists.
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
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With