Judgment method: 1. Use the "$("parent element").has("child element").length" statement. If the return value is 1, the specified child element exists; 2. Use "$ ("parent element").children("child element").length" statement, if the return value is greater than or equal to 1, the specified child element exists.
The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.
jquery determines whether the specified child element exists
Method 1: Use the has() method
has() Reduces the set of matching elements to the subset that has descendants that match the specified selector or DOM element.
<!DOCTYPE html> <html> <head> <script type="text/javascript" src="js/jquery-1.10.2.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("button").click(function() { if ($("div").has("span").length) { console.log("指定子元素存在") } else { console.log("指定子元素不存在") } }); }); </script> </head> <body> <div style="border: 1px solid red;"> <p>子元素1</p> <span>子元素2</span> </div><br> <button>指定子元素span是否存在</button> </body> </html>
Method 2: Use children()
The children() method returns all direct child elements of the selected element.
<!DOCTYPE html> <html> <head> <script type="text/javascript" src="js/jquery-1.10.2.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("button").click(function() { if ($("div").children("p").length) { console.log("指定子元素存在"); console.log($("div").children("p").length); } else { console.log("指定子元素不存在"); console.log($("div").children("p").length); } }); }); </script> </head> <body> <div style="border: 1px solid red;"> <p>子元素1</p> <span>子元素2</span> <span>子元素2</span> <p>子元素3</p> <p>子元素4</p> </div><br> <button>指定子元素是否存在</button> </body> </html>
[Recommended learning: jQuery video tutorial, web front-end】
The above is the detailed content of How to determine whether a specified child element exists in jquery. For more information, please follow other related articles on the PHP Chinese website!