Home >Web Front-end >JS Tutorial >How to find the parent class of a specified element in jquery
Jquery method to find the parent class of a specified element: 1. Use the [closest()] method to return the first ancestor of the selected element; 2. Use the [parent()] method to return the selected element The element's immediate parent.
The operating environment of this tutorial: windows7 system, jquery3.2.1 version, DELL G3 computer.
Recommended: jquery video tutorial
##jquery method to find the parent class of a specified element:
In jquery, you can use the closest() method and parent() method to find the parent class of a specified element.closest() method is used to return the first ancestor of the selected element.
parent() method is used to return the direct parent element of the selected element.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body style="text-align:center;"> <p style= "font-size: 17px; font-weight: bold;">点击按钮,查看结果</p> <div class="parent"> <div class="child"></div> </div> <button>点击</button> <p id="DOWN" style="color: green; font-size: 24px; font-weight: bold;"> </p> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $('button').on('click', function() { var object = $('.child').closest('.parent'); if (object.length) { $('#DOWN').text("className = '.child'" + ",parentName = '.parent'"); } else { $('#DOWN').text("不存在父类"); } }); </script> </body> </html>Rendering: Example 2: Use the parent() method to get the direct parent element of the element
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> .ancestors *{ display: block; border: 2px solid lightgrey; color: lightgrey; padding: 5px; margin: 15px; } </style> <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"> </script> <script> $(document).ready(function(){ $("span").parent("li").css({"color":"red","border":"2px solid red"}); }); </script> </head> <body class="ancestors">body (曾曾祖父节点) <div style="width:500px;">div (曾祖父节点) <ul>ul (祖父节点) <li>li (直接父节点) <span>span</span> </li> <li>li (直接父节点) <span>span</span> </li> </ul> </div> </body> </html>Rendering:
Related free learning recommendations: javascript(Video)
The above is the detailed content of How to find the parent class of a specified element in jquery. For more information, please follow other related articles on the PHP Chinese website!