We help IT Professionals succeed at work.

jquery check if div not empty and visble

Luey
Luey used Ask the Experts™
on
Hello I need to check to see if a div is visible and not empty at the same time in Jquery.
I have figured out how to check if it is not empty and also to check if it is visible, but I do not how to write the code so I can check both at once.
Thanks

This works to see if the div is not empty
if ($('#cls_image1').html().trim()) {
    alert('Proceed as element is not empty.');
  } 

Open in new window


This works to see if the div is visible
if ($('#cls_image1').is(':visible')) {
    alert('Proceed as element is not empty.');
  }

Open in new window


This does not work to check both
if ($('#cls_image1').is(':visible').html().trim()) {
    alert('Proceed as element is not empty.');
  }

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
var element = $('#cls_image1');
if (element.html().trim() && element.is(':visible')) {
    alert('Proceed as element is not empty.');
  }
Multitechnician
Top Expert 2014
Commented:
if ($('#cls_image1').is(':visible') && $('#cls_image1').html().trim()) {
    alert('Proceed as element is not empty.');
  }

Open in new window

i should explain my answer a little better...

a big drawback in jquery is it encourages people to write inefficient js. by storing "$('#cls_image1')" in a variable we avoid looking it up twice
the "normal" way i have seen people write jquery is to call "$" every time they want to perform an operation on an element even if they just looked it up in the previous statement.

this is important because JS interaction with the DOM is a relatively slow operation. doesn't matter when you only have a small dom and little js but where i work we have 30,000 lines of js and massive pages and then it matters A LOT.

Author

Commented:
Both worked but I used leakim971's answer as I did not want to introduce a variable in my situation.  Thanks for the syntax lesson. :)

Author

Commented:
Hey thanks basicinstinct I only have about 20 lines of javascript so prob not gonna hurt me.  However I am glad to know that. Thanks
yeah it won't hurt unless your html pages are really large.

still at my work if a developer produced that code it would be sent back for rewrite, just so you know...