Hi i want to access the first div with class "icon" using getByTestId.
below is how the DOM looks,
<div class="parent">
<div data-testid="add">
<div class="info"></div>
<div class="action">
<div class="icon"/> //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>
As you see from above there are multiple elements with testid "add" how can i get the first add div and access its child div with class icon.
i have tried
const element = queryAllByTestId('add')[0].querySelector(
'div'
)[1];
this gives element undefined.
could someone help me with this. thanks.
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
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With