Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether a DIV contains Image or not

Tags:

jquery

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>
like image 987
Solvonix Avatar asked Jan 18 '13 12:01

Solvonix


People also ask

How do you check if a div contains an image?

$(this). find('> img'). length could also be written as $(this). children('img').

How to check element is exists or not?

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.

How do I check if a div contains an element?

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.

How to check div is exist or not in jQuery?

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.


2 Answers

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
like image 124
Rory McCrossan Avatar answered Sep 30 '22 08:09

Rory McCrossan


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/

like image 36
charlietfl Avatar answered Sep 30 '22 06:09

charlietfl