How to determine whether an element exists in jquery

WBOY
Release: 2022-06-09 17:08:15
Original
1752 people have browsed it

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
Copy after login

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>
Copy after login

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 元素不存在");
}
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!