0) {the element exists and the specified code exists;}else{the element does not exist and the specified code;}"."/> 0) {the element exists and the specified code exists;}else{the element does not exist and the specified code;}".">

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

How to find whether a specified html element exists with jquery

WBOY
WBOYOriginal
2022-06-02 10:33:332082browse

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

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 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!

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