0) {//Exists }else {//Does not exist}"."/> 0) {//Exists }else {//Does not exist}".">

Home >Web Front-end >JS Tutorial >How does jquery determine whether an object exists?

How does jquery determine whether an object exists?

青灯夜游
青灯夜游Original
2020-11-19 15:39:062095browse

Jquery method to determine whether an object exists: use the length attribute to determine whether the number of elements in the object is greater than 0. If it is greater than 0, the object exists, otherwise it does not exist; syntax "if ($(selector).length > ; 0) {//Exists}else {//Does not exist}".

How does jquery determine whether an object exists?

Related recommendations: "jQuery Video"

1. Traditional Javascript writing method

obj = document.getElementById("someID"); 
if (obj){ 
   obj.innerText("hi"); 
}

In jQuery, var obj = $("#id") returns object regardless of whether the id control exists, so if(obj) cannot be used to determine whether the control exists

2. jQuery determines whether the object exists

Method 1:

if ($('#target_obj_id').length > 0) {
//如果大于0 标识 id 为target_obj_id的对象存在,否则不存在 
   //对象存在的处理逻辑 
} else { 
   //对象不存在的处理逻辑 
}

Method 2:

if ($('#target_obj_id')[0]) { 
  //对象存在的处理逻辑 
} else { 
  //对象不存在的处理逻辑 
}

For more programming-related knowledge, please Visit: Programming Learning Website! !

The above is the detailed content of How does jquery determine whether an object exists?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn