Table of Contents

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

  • A parent, a child and a grand child
<div class="parent">
  <div>
     <p>Grand Child</p>
  </div>   
  <p>Child</p>
</div>
  • 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
firstChild.style.color="darkviolet";
  • Output: