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"). Innertext ("Hi");
If the element whose ID is "someid" does not exist, we will get a javascript running error:Document. getelementbyid ("someid") is null
The correct statement should be:
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:
If($ ("# Someid")){
$ ("# Someid"). Text ("Hi");
}
However, this is wrong! Because jquery objects always return values$ ("Someid ")
AlwaysTrue
The IF statement does not have any judgment function. The correct statement should be:
If($ ("# Someid").Length> 0 ){
$ ("# Someid"). Text ("Hi");
}
note : it is not necessary to determine whether a page element exists in jquery, jquery performs ignore operations on a nonexistent element and does not report an error.