How to Select All Child Elements Recursively in CSS

A child selector matches all child elements of a specified element. It is composed of two or selectors that are separated by ">".

A child selector has the following syntax:

element > element

This syntax selects all child elements. If you want to select child elements recursively, use the syntax below.

div.class,
div.class>* {
  // CSS Property
}

First, we’ll explain how to select all child elements.

Create HTML

  • Place two <span> elements inside a <div>, then add another <span> inside a <p> .
  • Add two more <span> elements after <div>.
<div>
  <span>Paragraph 1</span>
  <span>Paragraph 2</span>
  <p>
    <span>Paragraph 3</span>
  </p>
</div>
<span>Paragraph 4</span>
<span>Paragraph 5</span>

Add CSS

  • Add the display property set to "block" for all the <span> elements.
span {
  display: block;
}
  • Add a child selector and set the background-color property.
div>span {
  background-color: #9ba2a3;
}

Let’s see the full code.

Example of selecting all child elements:

<!DOCTYPE html> 
<html>
  <head>
    <title>Title of the document</title>
    <style> 
      span {
      display: block;
      }
      div > span { 
      background-color: #9ba2a3; 
      } 
    </style>
  </head>
  <body>
    <div>
      <span>Paragraph 1</span>
      <span>Paragraph 2</span>
      <p>
        <span>Paragraph 3</span>
      </p>
    </div>
    <span>Paragraph 4</span>
    <span>Paragraph 5</span>
  </body>
</html>

Now, we’ll discuss another example where we select all child elements recursively. In the following example, we use the second syntax mentioned above and add background color to the div class. The asterisk (*) matches any element.

Example of selecting all child elements recursively:

<!DOCTYPE html> 
<html>
  <head>
    <title>Title of the document </title>
    <style> 
      span {
      display: block;
      }
      div.example, div.example > * { 
      background-color: #9ba2a3; 
      } 
    </style>
  </head>
  <body>
    <div class="example">
      <span>Paragraph 1</span>
      <span>Paragraph 2</span>
      <p>
        <span>Paragraph 3</span>
      </p>
    </div>
    <span>Paragraph 4</span>
    <span>Paragraph 5</span>
  </body>
</html>

Do you find this helpful?

Related articles