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:

HTML:
<div id="holder">
<div id="element_id">Hello World!</div>
</div>

JavaScript (jQuery):
console.log( $('#element_id').length )

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

example:

HTML:
<div id="holder">
</div>

JavaScript (jQuery):
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. Remove DOM Element with JQuery