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


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:

Powered by ComboStrap