Cypress: Get an array of webelements

Viewed 2127

This might be a simple question, or something that cannot be done. But I find Cypress help on the net to be a bit "behind" compared to Selenium resources. Furthermore, being a Java programmer, I'm struggling a bit to come to terms with what I can and cannot do in TypeScript (as well as in Cypress compared to Selenium).

Is it at all possible, in Cypress (and TypeScript) to get an array of WebElements from code like this?

<div id="row-123">
   <span id="comment">
   <button id="purge>
   <input id="comment">
</div>
<div id="row-456">
   <span id="comment">
   <button id="purge>
   <input id="comment">
</div>
<div id="row-789">
   <span id="comment">
   <button id="purge>
   <input id="comment">
</div>

I'm trying with this:

var rows = Array(cy.get('*[id^="row"]'));

But when I try asserting the length of the rows[] array, it claims to be 1 instead of 3. So it doesn't work like I thought it would.

In Java and Selenium, I'd do something like this:

List<WebElement> rows = driver.findElements(By.id("^row"));

Then I could use for instance Stream() to parse each element into a class which then accessed the (sub)elements inside that. And so on. But I find this difficult to do in Cypress?

1 Answers

You can use each() to iterate through an array like structure (arrays or objects with a length property).

let idArray = []
cy.get('*[id^="row"]').each(($el, index, $lis) => {
    //Find element based on InnerText
    if ($el.text() == 'text') {
        //Do something  
    }
    //Find element based on index position
    if (index == 1) {
        //Do something
    }
    //Save the id in the idArray
    cy.wrap($el).invoke('attr', 'id').then((val) => {
        idArray.push(val);
    })
}).then(($lis) => {
    expect($lis).to.have.length(3)
})

As per the discussion, a way to iterate over multiple tr's and td's and find the desired element based on innerText and then take some actions:

cy.get('tr').each(($el, index, $lis) => {
    cy.get('td').each(($el) => {
        if ($el.text() == 'text') {
            cy.log('Element found')
            return
        }
    })
})
Related