Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select All Elements in Subtree

Tags:

css

How can I make a CSS selector match all elements in the subtree of an element marked with a certain class?

I'm imagining CSS like the following (where the :subtree part is me making something up).

.diagram:subtree
{
    ...
}

When I write HTML like the following, the <div> and every element inside of it should be selected.

<div class="diagram">
    ...
</div>
like image 493
Timothy Shields Avatar asked Mar 09 '26 17:03

Timothy Shields


2 Answers

Simply use the descendant selector (space):

.diagram * { … }

This selects every element beneath any element(s) that have the diagram class applied.

To match both the div itself AND its descendants, use grouping:

.diagram, .diagram * { … }

Quoting the spec:

At times, authors may want selectors to match an element that is the descendant of another element in the document tree (e.g., "Match those EM elements that are contained by an H1 element"). Descendant selectors express such a relationship in a pattern. A descendant selector is made up of two or more selectors separated by white space. A descendant selector of the form "A B" matches when an element B is an arbitrary descendant of some ancestor element A.

like image 140
Phrogz Avatar answered Mar 12 '26 06:03

Phrogz


.diagram, .diagram *

This will select the div .diagram. The space is the descendant selector, and * is all elements.

EDIT: I thought your question originally said "including the element" hence the .diagram,, but you can simply remove that if desired.

like image 30
Explosion Pills Avatar answered Mar 12 '26 07:03

Explosion Pills



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!