• jQuery Video Tutorials

jQuery :parent Selector



The :parent selector in jQuery is used to select elements that have at least one child element (either an element or text node). In other words, It filters the set of matched elements to only those that have one or more child nodes of any type (including text nodes).

Syntax

Following is the syntax of :parent selector in jQuery −

$(":parent")

Parameters

Following are the parameters of this method −

  • ":parent" − This selector selects elements that have at least one child element or text node.

Example 1

This example demonstrates using the :parent selector to highlight all non-empty

elements by changing their background color −
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("div:parent").css("background-color", "lightblue");
        });
    </script>
</head>
<body>
    <div>Non-empty div with text</div>
    <div><p>Non-empty div with a paragraph</p></div>
    <div>   </div>
    <div></div>
</body>
</html>

After executing the above program, the parent div elements (which has at least one child element or text node) will be highlighted with lighblue background color.

Example 2

This example changes the font color of all non-empty

elements using the :parent selector −

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("p:parent").css("color", "blue");
        });
    </script>
</head>
<body>
    <p>This is a non-empty paragraph.</p>
    <p><span>Another non-empty paragraph with a span.</span></p>
    <p>     </p>
    <p></p>
</body>
</html>

After executing the above program, the parent "p" elements (which has at least one child element or text node) will be highlighted with blue color.

jquery_ref_selectors.htm
Advertisements