0) {$("#someID").text("hi");}" How to determine whether the element exists."/> 0) {$("#someID").text("hi");}" How to determine whether the element exists.">

Home  >  Article  >  Web Front-end  >  jquery finds whether element exists

jquery finds whether element exists

藏色散人
藏色散人Original
2021-01-18 09:10:504059browse

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");

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");
}

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");
}

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");
}

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!

Statement:
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