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 >Web Front-end >Front-end Q&A >How to find whether a specified html element exists with jquery
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;}".
The operating environment of this tutorial: windows10 system, jquery3.2.1 version, Dell G3 computer.
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 ($('#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 As follows:
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!