Home > Web Front-end > JS Tutorial > jquery finds whether element exists

jquery finds whether element exists

藏色散人
Release: 2022-12-30 11:11:58
Original
4076 people have browsed it

Jquery method to find whether an element exists: first create a front-end sample file; then pass "if($("#someID").length>0 ) {$("#someID").text(" hi");}" method can be used to determine whether the element exists.

jquery finds whether element exists

The demonstration environment of this tutorial: windows7 system, jquery1.2.6 version, Dell G3 computer.

Recommended: jQuery video tutorial

jquery determines whether an element exists

In traditional Javascript Here, before we perform some operation on a page element, it is best to first determine whether the element exists. The reason is that operations on an element that does not exist are not allowed. For example:

document.getElementById("someID").innerText("hi");
Copy after login

If the element with the ID "someID" does not exist, we will get a Javascript run error: document.getElementById("someID") is null

The correct writing method should be:

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

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:

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

But this is wrong! 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:

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

Note: It is actually not necessary to judge whether a certain page element exists or not in jQuery. jQuery itself will ignore the operation of a non-existent element and will not report an error.

The above is the detailed content of jquery finds whether element exists. For more information, please follow other related articles on the PHP Chinese website!

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