How can I use previously cached selectors with certain aspects of querySelector() ?
For example, I have this HTML / JavaScript:
let L1, L2, L3;
L1 = document.querySelector('#L1');
L2 = L1.querySelector('div:nth-child(1)');
L2.classList.add('L2');
L3 = L1.querySelector('div:nth-child(2)');
L3.classList.add('L3');
console.log(L2);
console.log(L3);
<div id="L1">
<div id="L2">
<div id="L2a"></div>
<div id="L2b"></div>
</div>
<div id="L3"></div>
</div>
Notice that div#L2b gets the className 'L3' instead of div#L3 getting it.
What I really want to do is something like:
L3 = L1.querySelector('> div:nth-child(2)');
to force querySelector() to choose the correct nth-child(2). For example, as in this demo that does NOT cache the selectors:
let L1, L2, L3;
const $ = document.querySelector.bind(document);
L1 = document.querySelector('#L1');
L2 = L1.querySelector('div:nth-child(1)');
L2.classList.add('L2');
L3 = document.querySelector('div#L1 > div:nth-child(2)');
L3.classList.add('L3');
console.log(L2);
console.log(L3);
<div id="L1">
<div id="L2">
<div id="L2a"></div>
<div id="L2b"></div>
</div>
<div id="L3"></div>
</div>
Is there any way this can be done with the L1 cached selector?
In my real-world use case, the L1 selector looks more like:
const $ = document.querySelector.bind(document);
$('body > div > div#main > div:nth-child(3) > div:nth-child(1) > div > div#L1');
I cringe at typing that string before each of 15 selectors I must cache.