JQuery determines 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").innerHTML("hi");

If the element with ID "someID" does not exist, the Javascript running error: document. getElementById ("someID") is null.

The correct statement should be:

   obj = document.getElementById("someID");     if (obj){        obj.innerHTML("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") is always TRUE, and IF statements do not have any judgment function. The correct statement should be:

    if ( $("#someID").length > 0 ) {         $("#someID").text("hi");      } 

Note: It is unnecessary for jQuery to determine whether a page element exists or not. jQuery will ignore the operation on a nonexistent element and will not report an error.

$(document).ready(function(){       var value=$('#btn_delXml').length;       if(value>0){           alert('Extsts');         }else {           alert('not Extsts');         } }) 

Summary:

When the jQuery selector gets the page element, an object is returned no matter whether the element exists or not. For example:

var my_element = $("#element_Id" )
At this time, the variable my_element is an object. Since it is an object, this object has the length attribute. Therefore, you can use the following code to determine whether an element (object) exists:

if(my_element.length>0){     alert("element is exist.");  }else{      alert("element not be found");  } 









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.