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
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.
The operating environment of this tutorial: windows10 system, jquery3.4.1 version, Dell G3 computer.
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 ($('#myElement').length > 0) { // 存在 document.write("id 为 myElement 元素存在"); } else { document.write("id 为 myElement 元素不存在"); } document.write("<br>"); if ($('#xxx').length > 0) { // 存在 document.write("id 为 xxx 元素存在"); } else { document.write("id 为 xxx 元素不存在"); }
Output result:
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!