For example:
document.getElementById("someID").innerText ("hi");
If the element with the ID "someID" does not exist, we will get a Javascript run error: document.getElementById("someID") is null
The correct way to write it should be It is:
obj = document.getElementById("someID") ;
if (obj){
obj.innerText("hi");
}
So in jQuery, how do we determine whether a page element exists? If we refer to the traditional Javascript writing method above, the first way we think of must be:
if ($("#someID")){
$("#someID").text("hi");
}
But This is wrong to write! Because jQuery objects always have a return value, $("someID") is always TRUE, and the IF statement does not play any judgment role. The correct way to write it should be:
if ( $("# someID").length > 0 ) {
$("#someID").text("hi");
}
Note: To determine whether a page element exists or not No is actually not necessary in jQuery. jQuery itself will ignore operations on a non-existent element and will not report an error.
$(document).ready(function(){
var value=$('#btn_delXml').length;
if(value>0)
{
alert('Extsts');
}
else
{
alert('not Extsts');
}
})
The following are other instructions. Although similar, some text instructions
are At this time, different operations must be performed based on the content loaded on the page. At this time, it becomes particularly important to determine whether this element (or object) exists on the page. It would be more troublesome to write JavaScript to implement it, but jQuery can easily implement this function.
We know that when the jQuery selector obtains the element of the page, it will return an object regardless of whether the element exists. For example:
var my_element = $("#element_Id" )
The variable my_element at this time is an object. Since it is an object, this object has the attribute length. Therefore, the following code can be used to determine the element (object ) exists:
if(my_element.length>0) {
alert("element is exist.");
}else{
alert("element not be found");
}