Hierarchy

Understanding hierarchy is one of the most important steps when it comes to building custom selectors. Do not skip this section!

Every web element on a website adheres to a hierarchy. See the hierarchy for the search button on the Wikipedia page:

For the search button on Wikipedia in the above example, the hierarchy would be:

body > div > form > fieldset > button

Note that some elements are on the same level (see picture below). This means these elements are items in a list and siblings to each other. They cannot be defined in a hierarchical way as shown in the example above (with >). They can be either defined as a list (you will learn about it later in chapter Lists: Incremental CSS Selectors) or - which is a bit more advanced - as siblings (you will learn about it in the final chapter of this guide Addressing Siblings).

Strict and Loose Hierarchy

Strict hierarchy

Whenever you use >, the hierarchy is defined in a strict way - in the example above (body > div > form > fieldset > button), body MUST be followed by div and if not the selector will fail.

Loose hierarchy

Alternatively, you can use space to define a loose hierarchy, for example:

body button

This means that body is followed by button somewhere below and it doesn't matter if there are other elements between body and button.

Build Selectors Based on Hierarchy

In some cases, to build a selector, you may need to additionally define the hierarchy. You can simply define tags that follow each other, like this:

Strict hierarchy: tag1 > tag2 > tag3 > tag4 > tag5

Loose hierarchy: tag1 tag3 tag5 (did you note how tag2 and tag4 are skipped?)

Combination of strict and loose hierarchy: tag1 tag3 > tag4 (note how tag2 is skipped but tag4 strictly follows tag3)

And for any tag inside the hierarchy you can add attributes like this:

tag1[attribute='value'] > tag2[attribute='value']

tag1 > tag2[attribute='value']

tag1[attribute='value'] > tag2

For the example of the search button on Wikipedia, the list of selectors we built can be extended by these ones, and they will work just as well:

Strict hierarchy: body > div > form > fieldset > button[class*='pure-button']

Loose hierarchy: body form button[class*='pure-button']

Combination of strict and loose hierarchy: body > div button[class*='pure-button']

Video Tutorial: Selector Hierarchy

Last updated