Home > Web Front-end > Front-end Q&A > How to find whether a specified html element exists with jquery

How to find whether a specified html element exists with jquery

WBOY
Release: 2022-06-02 10:33:33
Original
2113 people have browsed it

In jquery, you can use the "if else" statement with the length attribute to find whether the specified html element exists. The syntax is "if (specified html element object.length > 0) {element exists specified code; }else{The element does not exist with the specified code;}".

How to find whether a specified html element exists with jquery

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

jquery finds whether the specified html element exists

We can use jQuery's length attribute to determine whether the id exists:

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

Grammar

$(selector).length
Copy after login

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 As follows:

How to find whether a specified html element exists with jquery

Video tutorial recommendation: jQuery video tutorial

The above is the detailed content of How to find whether a specified html element exists with 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