9

I want to access the first element with class "icon".

This is how the DOM looks:

<div class="parent">
    <div data-testid="add">
        <div class="info"></div> 
        <div class="action">
            <div class="icon"/> // <== I want to access this 
        </div>
    </div>
</div>
<div class="parent">
    <div data-testid="add">
        <div class="info"></div> 
        <div class="action">
            <div class="icon"/> 
        </div>
    </div>
</div>

How can I get the first div with class "icon"?

I have tried:

const element  = queryAllByTestId('add')[0].querySelector(
    'div'
  )[1];

This gives element undefined.

1 Answer 1

11

getAllBy

getAllBy* queries return an array of all matching nodes for a query, and throw an error if no elements match.

queryAllBy

queryAllBy* queries return an array of all matching nodes for a query, and return an empty array ([]) if no elements match.

Query Cheetsheet

enter image description here

Use the query variant so as not to throw in a test if no matches found, and use querySelectorAll since querySelector returns only the first element that matches, or null.

const element = queryAllByTestId("add");
if (element.length) {
  let divs = element[0].querySelectorAll("div");
  // ...get the div node you need
}

You can even specify divs with a specific class

const element = queryAllByTestId("add");
if (element.length) {
  let divs = element[0].querySelectorAll("div.icon");
  // ...get the div node you need
}
Sign up to request clarification or add additional context in comments.

4 Comments

thanks. i cannot use div.icon since the classname is added dynamically as i am using react + typescript..so should go with first option. but then querySelectorAll("div") gives all the divs under the div got by testid..how do i get second div (i.e., action) and get its firstchild (i.e., icon) without using class and something like div[1].firstChild...this doesnt work for me
@someuser2491 Is there any reason you can't also place a data-testid attribute on the icon div for testing? The other options are the boilerplate DOM "walking", or a more specific/targeted query selector, something like "div + div" to select the icon div child of the action div (Disclaimer: may need to be tweaked).
i dint want to add the data-testid. but since its tedious i would add it. so would it be queryAllByTestId('icon')[0] to select first icon div with testid icon?
@someuser2491 Yes, if the element is <div class="icon" data-testid="icon"/>, then you can query it via queryAllByTestId('icon')`. Remember though, it can return an empty array so you shouldn't assume to be able to directly array index into it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.