In the DOM structure provided, there are multiple div elements with different classes nested within each other.
<div id="container">
<div class="item"></div>
<div class="item"></div>
<div class="another-container">
<div class="item"></div>
</div>
<div class="item"></div>
<div class="another-container">
<div class="another-another-container">
<div class="item"></div>
</div>
</div>
</div>
The goal is to select the third element with the class ".item" while ignoring the other nested elements.
This can be achieved by using the following code:
document.querySelectorAll('.item')[2].dataset.isSelected = true;
While this method works, for large DOM structures where this operation is performed frequently, it might not be efficient to query all elements (
document.querySelectorAll('.item')
) just to get one specific element.
- Is there a more optimized way to achieve this? (apart from converting the list of
.item
elements into a static array) - Alternatively, does
querySelectorAll
dynamically fetch elements at runtime instead of retrieving them all at once?