Home > Web Front-end > JS Tutorial > jQuery code to determine whether page elements exist_jquery

jQuery code to determine whether page elements exist_jquery

WBOY
Release: 2016-05-16 18:48:08
Original
952 people have browsed it

For example:

Copy code The code is as follows:

document.getElementById("someID").innerText ("hi");

If the element with the ID "someID" does not exist, we will get a Javascript run error: document.getElementById("someID") is null
The correct way to write it should be It is:
Copy code The code is as follows:

obj = document.getElementById("someID") ;
if (obj){
obj.innerText("hi");
}

So in jQuery, how do we determine whether a page element exists? If we refer to the traditional Javascript writing method above, the first way we think of must be:
Copy the code The code is as follows:

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

But This is wrong to write! Because jQuery objects always have a return value, $("someID") is always TRUE, and the IF statement does not play any judgment role. The correct way to write it should be:
Copy code The code is as follows:

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

Note: To determine whether a page element exists or not No is actually not necessary in jQuery. jQuery itself will ignore operations on a non-existent element and will not report an error.
Copy code The code is as follows:

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

The following are other instructions. Although similar, some text instructions
are At this time, different operations must be performed based on the content loaded on the page. At this time, it becomes particularly important to determine whether this element (or object) exists on the page. It would be more troublesome to write JavaScript to implement it, but jQuery can easily implement this function.
We know that when the jQuery selector obtains the element of the page, it will return an object regardless of whether the element exists. For example:
var my_element = $("#element_Id" )
The variable my_element at this time is an object. Since it is an object, this object has the attribute length. Therefore, the following code can be used to determine the element (object ) exists:
Copy code The code is as follows:

if(my_element.length>0) {
alert("element is exist.");
}else{
alert("element not be found");
}
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template