Let say I have the following code:
let testA = document.querySelectorAll('.vehicle')
Let say I have this html
<div class="vehicle">
// some stuff
</div>
<div class="vehicle">
// some stuff
</div>
I know querySelectorAll
will select all the classes on the page but is there a way to use querySelectorAll
to just select the items from the first vehicle div
class to do something. Then use querySelectorAll from the second vehicle div class
to do something?
2
Answers
Yes, you can achieve this by using the :nth-child()
let firstVehicleElements = document.querySelectorAll(‘.vehicle:nth-child(1)’);
let secondVehicleElements = document.querySelectorAll(‘.vehicle:nth-child(2)’);
You can adjust the nth-child() index according to the position of the .vehicle elements within their parent container.
You can use
The elements in the NodeList can be accessed by an index number.
To access the second node you can write:
myNodeList[1];