Home > Article > Web Front-end > jQuery detects whether an element has code sharing_jquery
There may be situations in the code where different operations are performed based on whether the element exists, so it is necessary to determine whether the specified element exists.
Use $(selector) to get the set of matching elements, and the length attribute of the set of matching elements can get the number of matching elements in the set, so as long as you determine whether the length attribute value is zero, you can determine whether the element exists. The code example is as follows:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>脚本之家</title> <script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#check").click(function(){ if($(".mytest").length>0){ alert("此元素存在"); } }) }) </script> <body> <ul> <li>太阳出来了</li> <li>脚本之家</li> <li class="mytest">div+css教程</li> </ul> <button id="check">点击检测</button> </body> </html>
If the number of elements in the collection is greater than zero, then the element exists, otherwise the specified element does not exist.
The above is the entire content of this article, I hope you all like it