0) {element exists specified code; }else{The element does not exist with the specified code;}"; if the number of elements is greater than 0, it means that the element exists."/> 0) {element exists specified code; }else{The element does not exist with the specified code;}"; if the number of elements is greater than 0, it means that the element exists.">

Home >Web Front-end >Front-end Q&A >How to determine whether an element exists in jquery

How to determine whether an element exists in jquery

WBOY
WBOYOriginal
2022-06-09 17:08:151837browse

In jquery, you can use the length attribute with the "if else" statement to determine whether an element exists. The length attribute is used to get the number of elements in the object. The syntax is "if(element object.length > 0) {The element exists with the specified code;}else{The element does not exist with the specified code;}"; if the number of elements is greater than 0, it means that the element exists.

How to determine whether an element exists in jquery

The operating environment of this tutorial: windows10 system, jquery3.4.1 version, Dell G3 computer.

How jquery determines whether element exists

The length property contains the number of elements in the jQuery object.

Grammar

$(selector).length

Just use the "if else" statement to make a judgment.

If the number of returned elements is greater than zero, the specified element exists;

The example is as follows:

html code is as follows:

<script src="hjs/jquery.min.js"></script>
<p id="myElement">
</p>

jquery code is as follows:

if ($(&#39;#myElement&#39;).length > 0) { 
// 存在
    document.write("id 为 myElement 元素存在");
} else {
document.write("id 为 myElement 元素不存在");
}
document.write("<br>");
if ($(&#39;#xxx&#39;).length > 0) { 
// 存在
    document.write("id 为 xxx 元素存在");
} else {
document.write("id 为 xxx 元素不存在");
}

Output result:

How to determine whether an element exists in jquery

Video tutorial recommendation: jQuery video tutorial

The above is the detailed content of How to determine whether an element exists in jquery. 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