English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

jQuery code to check if an element exists as an instance on the page

    Recently, while doing a project, I encountered a feature to check whether an element exists on the web page using jQuery, so I record it here, which may help friends who are reading this article.

 When checking whether an element exists on the web page using jQuery, you should judge according to the length of the element obtained, as shown in the following code:

if($("#tt").length > 0) {
  //Code executed when the element exists
}  

The specific reasons are as follows:

         In JavaScript, when we use the traditional getElementById() and getElementsByTagName(), if we cannot find the relevant elements on the web page, the browser will report an error, affecting the execution of subsequent code. Therefore, in order to avoid browser errors, we can judge the elements, for example:

if(document.getElementById("tt")) {//js judge if element exists
  document.getElementById("tt").style.color = "red";
}

  If there are many elements to be operated, a lot of repetitive work is needed, which is often tedious. One of the major advantages of jQuery is its comprehensive handling mechanism, which means that even if you use jQuery to get an element that does not exist on the web page, it will not report an error. This is because $("#tt") always gets an object, even if there is no such element on the web page. Therefore, when using jQuery to check whether an element exists on the web page, you cannot use the following code:

if($("#tt")) {
  //Always execute, regardless of whether the element exists
}

  This is why it is necessary to judge whether an element exists on the page according to the length of the element.

       Thank you for reading, I hope it can help everyone, thank you for your support to our website!  

You May Also Like