skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. You can use

    const myNodeList = document.querySelectorAll(".vehicle");
    

    The elements in the NodeList can be accessed by an index number.
    To access the second node you can write:
    myNodeList[1];

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search