Home > Web Front-end > JS Tutorial > body text

jQuery method to determine whether an object exists_jquery

WBOY
Release: 2016-05-16 16:15:41
Original
1001 people have browsed it

The example in this article describes how jQuery determines whether an object exists. Share it with everyone for your reference. The details are as follows:

1. Traditional Javascript writing method

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

Copy after login

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 { 
   //对象不存在的处理逻辑 
}
Copy after login

Method 2:

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

I hope this article will be helpful to everyone’s jQuery programming.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!