How to know whether an element existed with jQuery

For the reference. In general javascript we can check for the existence of an element using the method below:

if(document.getElementById('element_id')) {
  //element exists
} else  {
  //element does not exist
}


In jQuery there is a simple approach to do the same check:

if($('#element_id').length) {
  //element exists
} else  {
  //element does not exist
}

Moreover, if you want to know whether one or more <img /> tag or <p> tags exist inside an element by given id, you can do it same way. For example,

if($('#element_id img').length) {
  //images exist
} else  {
  //images do not exist
}

or

if($('#element_id p').length) {
  //paragraphs exist
} else  {
  //paragraph do not exist
}

Thats it!

Leave a Reply