532

How can you select all child elements recursively?

div.dropdown, div.dropdown > * {
    color: red;
}

This class only throws a class on the defined className and all immediate children. How can you, in a simple way, pick all childNodes like this:

div.dropdown, 
div.dropdown > *, 
div.dropdown > * > *, 
div.dropdown > * > * > *, 
div.dropdown > * > * > * > * {
    color: red;
}

3 Answers 3

819

Use a white space to match all descendants of an element:

div.dropdown * {
    color: red;
}

x y matches every element y that is inside x, however deeply nested it may be - children, grandchildren and so on.

The asterisk * matches any element.

Official Specification: CSS 2.1: Chapter 5.5: Descendant Selectors

Sign up to request clarification or add additional context in comments.

9 Comments

it works, but now it overrides all other classes even if they have a higher priority.. (they are placed later in the css file)
The selector also plays a role in what priority the properties have, not just where in the file they appear. You could try adding ` !important` to your values, e.g. color: red !important;
I know, it's a bit ugly. You could instead try writing more precise selectors, chances are, this would work too. (e.g. #head ul#head ul#navi)
Okay, very basic example: p.xy is more important than p, because it is kind of more specific. jsfiddle.net/ftJVX
what if I want all child that had a specific class?
|
222

The rule is as following :

A B {
  /* B is descendant of A */
}
A > B {
  /* B is direct child of A */
}

So

div.dropdown *

instead of

div.dropdown > * 

Comments

1

Descendant combinator

The descendant combinator — typically represented by a single space (" ") character — combines two selectors such that elements matched by the second selector are selected if they have an ancestor (parent, parent's parent, parent's parent's parent, etc.) element matching the first selector.

details details {
  margin-left:48px;
}
<details>
  <summary>A</summary>
  A is a letter in the alphabet.
</details>
<details open>
  <summary>B</summary>
  B is a letter in the alphabet.
  <details open>
    <summary>1</summary>
    1 is a number.
    <details open>
      <summary>*</summary>
      * is a character.
    </details>
  </details>
  <details open>
    <summary>2</summary>
    2 is a number.
  </details>
</details>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.