0) {//Exists }else {//Does not exist}"."/> 0) {//Exists }else {//Does not exist}".">
Home > Article > Web Front-end > How does jquery determine whether an object exists?
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}".
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!