jQuery parents() method
The parents() is also an inbuilt method in jQuery that is used to find all the parent elements of the selected element. This parents() method in jQuery traverses all the levels up and returns all parent elements of the selected element.
Syntax:
$('element_selector').parents()
Parameters:
It accepts an optional parameter to filter the parents by passing their IDs or classes to it.
Return value:
It returns all the parents of the selected element.
Example: The below code example will explain the use of the parents() method of jQuery.
html
<!DOCTYPE html> < html > < head > < style > .main_body{ display: flex; align-items: center; justify-content: center; } .main_body * { display: block; border: 2px solid green; color: green; padding: 5px; margin: 15px; } </ style > < script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" > </ script > < script > $(document).ready(function () { $("span").parents().css({ "color": "#000", "border": "2px solid #000" }); }); </ script > </ head > < body class = "main_body" > < div style = "width:500px;" > This is the great grand parent of the selected span element.! < ul > This is the grand parent of the selected span element.! < li > This is the parent of the selected element.! < span > This is the selected span element.! </ span > </ li > </ ul > </ div > </ body > </ html > |
Output:
jQuery is an open-source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous for it’s philosophy of “Write less, do more”. You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.
jQuery parent() & parents() Method
In this article, we will learn about the parent() and the parents() methods of jQuery in detail with their practical implementation using the code examples.
Table of Content
- jQuery parent() method
- jQuery parents() method
Contact Us