Determine whether a page element exists

Source: Internet
Author: User

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 ")AlwaysTrueThe 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.

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.