In traditional Javascript, it is best to determine whether a page element exists before performing some operations on a page element. The reason is that operations on a nonexistent element are not allowed.
For example:
document.getElementById("someID").innerHTML("hi");
If the element with ID "someID" does not exist, the Javascript running error: document. getElementById ("someID") is null.
The correct statement should be:
obj = document.getElementById("someID"); if (obj){ obj.innerHTML("hi"); } In jQuery, how do we determine whether a page element exists or not? If we refer to the traditional Javascript writing method above, the first method we come up with must be:
if ($("#someID")){ $("#someID").text("hi"); }
However, this is wrong! Because jQuery objects always return values, $ ("someID") is always TRUE, and IF statements do not have any judgment function. The correct statement should be:
if ( $("#someID").length > 0 ) { $("#someID").text("hi"); }
Note: It is unnecessary for jQuery to determine whether a page element exists or not. jQuery will ignore the operation on a nonexistent element and will not report an error.
$(document).ready(function(){ var value=$('#btn_delXml').length; if(value>0){ alert('Extsts'); }else { alert('not Extsts'); } })
Summary:
When the jQuery selector gets the page element, an object is returned no matter whether the element exists or not. For example:
var my_element = $("#element_Id" )At this time, the variable my_element is an object. Since it is an object, this object has the length attribute. Therefore, you can use the following code to determine whether an element (object) exists:
if(my_element.length>0){ alert("element is exist."); }else{ alert("element not be found"); }