How can I define the actual / context element in a CSS selector ? Short Answer: the scope pseudo-class

Chrome Devtool Selector


When chaining selection with the querySelector, you may need to perform selection in the context of the actual selected node.

This article shows you how to do it.

The short answer is that you need to use the :scope 1) pseudo-class in your selector

Demo: The first child of a element with querySelector

  • A parent, a child and a grand child
<div class="parent">
     <p>Grand Child</p>
  • Let say that you first select the parent to modify it (such as modifying some attribute). You would first select it.
// select the first node with the class parent as descendant in the document
let parentNode = document.querySelector(".parent") 
  • Then you want to select the first child of this node. To do that, you can still perform a selection with the child selector (>) using the :scope pseudo-class.
// select the first p of the parentNode
firstChild = parentNode.querySelector(":scope > p"); 
// color it"darkviolet";
  • Output:

Discover More
How to select the first child of a node element with DOM ? (Javascript examples)

This article shows you how to select the first child element. The best way to get the first child of a parent is through the child selector (>) Example: A parent, a child and a grand child...
Chrome Devtool Selector
Selector API

API A selector is a boolean expression (known also as predicate) that match against elements in a DOM tree in order to select one or several node. This API was known before as the CSS and was renamed...

Share this page:
Follow us:
Task Runner