For example:
Copy codeThe Code is as follows:
Document. getElementById ("someID"). innerText ("hi ");
If the element with ID "someID" does not exist, the Javascript running error: document. getElementById ("someID") is null.
The correct statement should be:
Copy codeThe Code is as follows:
Obj = document. getElementById ("someID ");
If (obj ){
Obj. innerText ("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:
Copy codeThe Code is as follows:
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:
Copy codeThe Code is as follows:
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.
Copy codeThe Code is as follows:
$ (Document). ready (function (){
Var value = $ ('# btn_delXml'). length;
If (value> 0)
{
Alert ('extsts ');
}
Else
{
Alert ('not extsts ');
}
})
The other descriptions are similar, but some text descriptions are as follows:
Sometimes, you need to perform different operations based on the content loaded on the page. In this case, it is especially important to determine whether the element (or object) exists on the page. If JavaScript is written for implementation, it is troublesome, but jQuery can easily implement this function.
We know that 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:
Copy codeThe Code is as follows:
If (my_element.length> 0 ){
Alert ("element is exist .");
} Else {
Alert ("element not be found ");
}