This article mainly introduces jQuery's reliable method for determining whether an element exists. If you need it, you can refer to the simplest method to determine the matching length of an element.
For example, HTML code:
The Code is as follows:
Generally, our approach is
The Code is as follows:
If ($ ('. myp'). length> 0)
Reliable and error-free practices:
The Code is as follows:
If ($ ('. myp'). length & $ ('. myp'). length> 0)
Return true;
The traditional javascript method is as follows:
The Code is as follows:
If (document. getElementById ('P ')){
// Find the corresponding element
} Else {
// No corresponding element found
}
JQuery is relatively simple. You only need to determine whether the length of this element is 0. If it is 0, this element does not exist. The Code is as follows:
The Code is as follows:
If ($ ("# p"). length> 0 ){
// Locate the element corresponding to id = p, and then execute the code
}
You can even find the combination element, as shown below. Let's find out whether the element with the id defined as p contains img. The Code is as follows:
The Code is as follows:
If ($ ("# p img"). length> 0 ){
// Find the corresponding id = p and contain the img element, and then execute the code
}
Is it easy? You can try it.