JQuery is a reliable way to determine the existence of elements

  • 2020-03-30 02:51:02
  • OfStack

The easiest way is to determine the element's matching length

For example, HTML code:

<div class='mydiv'></div>

What we usually do is


The more reliable and error-proof approach is:

if($('.mydiv').length && $('.mydiv').length>0)
  return true;


Use the traditional javascript approach as follows:

if(document.getElementById('div')) {     
    //Find the corresponding element
} else {     
    //No corresponding element was found

Using jQuery is relatively simple. You only need to determine whether the length of this element is 0. If it is 0, this element does not exist.

if ($("#div").length > 0){ 
    //Find the element with the corresponding id=div, and then execute the block

We can even find the composite elements, as follows: we can find whether img is contained in the element whose id is defined as div. The code is as follows:

if ($("#div img").length > 0){ 
    //Find the element that corresponds to id=div and contains img, and then execute this block of code

Isn't that easy? You can try it out

Related articles: