To select all child elements of a given element, you can use a descendant selector in combination with the universal selector(*
). The universal selector is represented by an asterisk(*
) and selects every element regardless of its type.
Let’s say we have a div element which has several child elements:
<div> <p>This is a child paragraph</p> <span>This is a child span</span> <h3>This is a child heading</h3> <span> <p>This is a nested child paragraph</p> </span> </div> <p>I am not a child of the div</p>
Now, we want to select every element that is the child of this div.
To do that, we will use a white space between the div and the universal selector(*). The universal selector will select every element that is the child of this div.
This is how you can do it:
/*Select every child of the div*/ div *{ background: yellow; }
Result after applying above styles:
![Select all child elements using css](https://programmersportal.com/wp-content/uploads/2022/08/select-all-child-of-the-div-1.png)
Select all Direct Child Elements
In the above example, we selected all child elements of the div i.e. including those elements too, which were not the direct children of the div element.
So, if you want to select only those child elements of the div which are the direct children of it, you have to put a greater than(>
) symbol in place of the white space.
The greater than(>
) symbol in CSS basically indicates the child selector.
/*Select every direct child of the div*/ div > *{ background: yellow; }
Now, this will select only the direct children of the div. See the below image:
![Select all direct child elements using css](https://programmersportal.com/wp-content/uploads/2022/08/select-all-direct-children-of-the-div.png)
Thanks for reading.