jQuery check for element visibility

What if the element exists in the DOM

That was described in my recent post and it describes the case when you have a particular element in the DOM tree, or if that element does not exists.

example:

<div id="holder">
<div id="element_id">Hello World!</div>
</div>
console.log( $('#element_id').length )

this prints 1, because the element exists. In the following example is different.

example:

<div id="holder">
</div>
console.log( $('#element_id').length )

that returns 0, because obviously the element does not exists.

So far so good, but what if the element exists and it’s not visible

Well than the HTML look like that:

example:

<div id="holder">
  <div id="element_id" style="display:none">
    Hello World!
  </div>
</div>

The solution is a bit different, but simple

jQuery code:

    if ($('#element_id:visible').length > 0)
         console.log('the element is visible');
    else
         console.log('the element is not visible');

8 thoughts on “jQuery check for element visibility

  1. Following have some options for check visibility.

    if( $('#foo').is(':visible') ) {
      // it's visible, do something
    }
    else {
      // it's not visible so do something else
    }

    Check if an element is hidden

    if( $('#foo').is(':hidden') ) {
      // it's hidden, do something
    }
    else {
      // it's not hidden so do something else
    }

    Looping though visible elements

    abc
    def
    ghi

    To loop through the visible divs under #foo do something do this:

    $("#foo div:visible").each( function() {
    	    document.write($(this).html()+'');
    });

    The above example would write the following out to the document:

    abc
    ghi

    Cheerssss !

  2. You always might do as it:
    if( $(‘#foo’).is(‘:visible’) ) {
    // it’s hidden, do something
    }
    else {
    // it’s not hidden so do something else
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>