Link to home
Start Free TrialLog in
Avatar of Luey
LueyFlag for United States of America

asked on

jquery check if div not empty and visble

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

SOLUTION
Avatar of basicinstinct
basicinstinct
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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.
Avatar of Luey

ASKER

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. :)
Avatar of Luey

ASKER

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...