Open In App
Related Articles

How to select all child elements recursively using CSS?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Using the child selector, you can select child elements. To select all child elements recursively, use the universal selector(*). A child selector matches when an element is the child of some element. A child selector is made up of two or more selectors separated by “>”. It is also known as element > element selector. It selects all elements of a specific parent.

Syntax:

  • Select all child elements.

parentSelector > * {
// CSS Styles
}

  • To select all the child elements of an element recursively

.parentSelector * {
// CSS Styles
}

Example 1: This example shows that how we can select elements that are direct children of GFG class.

html

<!DOCTYPE html>
<html>
 
<head>
    <title>
        Child element selector
    </title>
 
    <style>
        .GFG>* {
            background-color: green;
        }
    </style>
</head>
 
<body>
    <div class="GFG">
        <p>Paragraph 1</p>
        <p>Paragraph 2</p>
        <span>
            <p>Paragraph 3</p>
        </span>
        <p>Paragraph 4</p>
    </div>
    <p>Paragraph 5</p>
</body>
 
</html>

                    

Output:

Screenshot-2024-01-15-222227

Example 2: This example shows how to selects to select all the child elements of an element recursively.

html

<!DOCTYPE html>
<html>
 
<head>
    <title>
        Child element selector
    </title>
 
    <style>
        .GFG * {
            background-color: green;
        }
    </style>
</head>
 
<body>
    <div class="GFG">
        <p>Paragraph 1</p>
        <p>Paragraph 2</p>
        <span>
            <p>Paragraph 3</p>
            <ul>
                <li>Item1</li>
                <li>Item2</li>
            </ul>
        </span>
    </div>
 
    <p>Paragraph 4</p>
    <p>Paragraph 5</p>
 
</body>
 
</html>

                    

Output:

Screenshot-2024-01-15-223711

CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.



Last Updated : 29 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads