Reliable method for jQuery to determine whether an element exists _ jquery

Source: Internet
Author: User
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.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.