Suppose we have some parent element, and other elements inside it:
<div id="parent">
<div class="child">text</div>
<div class="child">text</div>
<div class="child">text</div>
</div>
Let the reference to the parent has already been derived into a variable:
let parent = document.querySelector('#parent');
In this case, if necessary, we can search
for the selector within that parent,
rather than the entire document.
To do this, the search method must
be applied not to document
, but
to a variable containing our parent.
For example, let's find elements with
the child
class inside our parent:
let elems = parent.querySelectorAll('.child');
Given the element #parent
:
<div id="parent">
<p class="www">text</p>
<p class="www">text</p>
<p class="www">text</p>
<p class="ggg">text</p>
<p class="ggg">text</p>
<p class="ggg">text</p>
</div>
let parent = document.querySelector('#parent');
Find elements with the class www
inside the parent and store them in the
variable elems1
. Then find elements
with the class ggg
inside the parent
and store them in the variable elems2
.