jquery
  1. jquery-parent

jQuery parent()

The parent() method in jQuery is used to select the direct parent element of the selected element. It is a useful method that can be used to access and manipulate the DOM elements in your web page.

Syntax

The syntax for using the parent() method in jQuery is as follows:

$(selector).parent()

Here, the selector is the element that you want to select the parent for. This could be a class, ID, tag, or other appropriate selector.

Use

The parent() method is used to select the direct parent element of the selected element. This can be useful in situations where you need to manipulate the parent element or access its properties. For example, you might use the parent() method to change the background color of a table row when the cursor is hovered over it.

Example

Here is an example of using the parent() method in jQuery:

<!DOCTYPE html>
<html>
<head>
    <title>jQuery parent() Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        table, th, td {
              border: 1px solid black;
              border-collapse: collapse;
              padding: 10px;
        }

        tr:hover {
            background-color: yellow;
        }
    </style>
</head>
<body>
    <table>
        <tr>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Age</th>
        </tr>
        <tr>
            <td>John</td>
            <td>Doe</td>
            <td>30</td>
        </tr>
        <tr>
            <td>Jane</td>
            <td>Doe</td>
            <td>25</td>
        </tr>
        <tr>
            <td>Bob</td>
            <td>Smith</td>
            <td>40</td>
        </tr>
    </table>

    <script>
        $(document).ready(function() {
            $('td').mouseover(function() {
                $(this).parent().css('background-color', 'lightblue');
            });
            $('td').mouseout(function() {
                $(this).parent().css('background-color', 'initial');
            });
        });
    </script>
</body>
</html>
Try Playground

In this example, we have used the parent() method to access the parent tr element of the td element that the mouse is hovering over. We have then used the css() method to change the background color of the tr element when the mouse hovers over the td element.

Summary

The parent() method in jQuery is a useful method that enables you to access and manipulate the direct parent element of the selected element. It is easy to use and can be effective in a wide range of web development scenarios.

Published on: