jQuery check for element visibility

submit to reddit

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');

Related posts:

  1. jquery check for element existence in the DOM
  2. Toggle the visibility with jQuery
  3. cancel bubbling on element click with jQuery

You are a GREAT developer? Click here to answer the weekly quiz!

This entry was posted in javascript, micro tutorial and tagged , , . Bookmark the permalink.

6 Responses to jQuery check for element visibility

  1. Nilima Kadam says:

    Hi Good day,
    Thanks! this was really helpful & simple to integrate. Thanks, keep up the good work!

  2. Shikha says:

    Fantastic code in just two lines !!! Great job

  3. singsong says:

    Nice example works perfectly

  4. Bob says:

    for the visibility check you can use this:

    $(element).is(":visible");
  5. Ankur Dalal says:

    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 !

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> <pre lang="" line="" escaped="" highlight="">