The simplest way is to determine the matching length of elements.
For example, HTML code:
Copy codeThe Code is as follows: <div class = 'mydiv '> </div>
Generally, our approach is
Copy codeThe Code is as follows: if ($ ('. mydiv'). length> 0)
Reliable and error-free practices:
Copy codeThe Code is as follows:
If ($ ('. mydiv'). length & $ ('. mydiv'). length> 0)
Return true;
The traditional javascript method is as follows:
Copy codeThe Code is as follows:
If (document. getElementById ('div ')){
// 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:
Copy codeThe Code is as follows:
If ($ ("# div"). length> 0 ){
// Find the corresponding id = div element, and then execute the code
}
You can even find the combination element, as shown below. Let's find whether the element with id defined as div contains img. The Code is as follows:
Copy codeThe Code is as follows:
If ($ ("# div img"). length> 0 ){
// Find the corresponding id = div and the element that contains the img, and then execute the code
}
Is it easy? You can try it.