jQuery – check if an element exists

jQuery when used with selectors like element tag, class, id can potentially return a jQuery object with no element in it. Since jQuery contains number of elements present in DOM using the specified selector, we can use the length property to check if an element exists.

if ($('.someclassname').length > 0) {
  // element exists
}

jQuery Object for non-existing element

<div class="foo">I am in div</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
  $(function() {
    console.log(JSON.stringify($(".nonexistingclass")));
  });
</script>
The outcome from above code (in console) is:

{"length":0,"prevObject":{"0":{},"context":{},"length":1},"context":{},"selector":".nonexistingclass"}

jQuery Object for existing element

<div class="foo">I am in div</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
  $(function() {
    console.log(JSON.stringify($(".foo")));
  });
</script>
The outcome from above code (in console) is:

{"0":{},"length":1,"prevObject":{"0":{},"context":{},"length":1},"context":{},"selector":".foo"}
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments