W3docs

How to Select All Child Elements Recursively in CSS

Read our snippet and find out how to select all child element recursively in CSS. Use a child selector that matches all elements of a specified element.

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

A child selector has the following syntax:

element > element

This syntax selects only direct children. To select all descendant elements recursively (children, grandchildren, etc.), use a descendant selector with a space:

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.
  • Add a child selector and set the background-color property.
span {
  display: block;
}

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>

Result

<div class="demo px-2.5 mt-1 mb-5 not-prose"> <div> <span>Paragraph 1</span> <span>Paragraph 2</span> <p> <span>Paragraph 3</span> </p> </div> <span>Paragraph 4</span> <span>Paragraph 5</span> </div>

Now, we’ll discuss another example where we select all child elements recursively. In the following example, we use the descendant selector (space) to target all elements inside the div. 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 * {
        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>