Home > Article > Web Front-end > jQuery method to determine whether an object exists_jquery
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"); }
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 { //对象不存在的处理逻辑 }
I hope this article will be helpful to everyone’s jQuery programming.