Table of Contents

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

About

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

<div class="parent">
  <div>
     <p>Grand Child</p>
  </div>   
  <p>Child</p>
</div>
// select the first node with the class parent as descendant in the document
let parentNode = document.querySelector(".parent") 
// select the first p of the parentNode
firstChild = parentNode.querySelector(":scope > p"); 
// color it
firstChild.style.color="darkviolet";