Reputation: 175
ok, so here is the situation. I have a webpage where I add elements to a table, and when I add that element , the webpage automatically assign a number for it.
My question is: How can I get that number ? Because its automatically generated, so I have no way of knowing which number its going to be. The table is something like that:
Name Number
Orange 35
Apple 452
Lemon 77
And the code :
<tr data-id="77">
<td class="col col-md-5 text-left">
Lemon
</td>
<td class="col col-md-5 text-left">
77
</td>
</tr>
as you can see, the number 77 does not have a unique identifier and when I created Lemon, I have no way of knowing what that number would be.
My first idea was to get the element on the left, which is Lemon, because I know its name (its me who gives its name, using .type() and then try and getting the element to the right of Lemon, which will be a number that I have no idea what number its going to be.
Is that possible? Is there a better way to do it ?
Upvotes: 1
Views: 1334
Reputation: 1790
Some options:
cy.contains('td.col', 'lemon').siblings('td.col').invoke('text').as('lemonNumber');
// or
cy.contains('td.col', 'lemon').parent('tr').invoke('data', 'id').as('lemonNumber');
// or for each row
cy.get('tr').each((row, index) => {
cy.wrap(row).contains('td', /\w+/).invoke('text').as('rowName' + index);
cy.wrap(row).contains('td', /\d+/).invoke('text').as('rowNumber' + index);
});
Upvotes: 0
Reputation: 23483
Without knowing what the exact number content is or a distinguishing feature of the containing element, you will need one of relative-selecting commands,
cy.contains('td', 'Lemon')
.siblings().eq(0)
.invoke('text')
.then(lemonText => {
const lemonNumber = +lemonText.trim();
// do something with lemonNumber
})
cy.contains('td', 'Lemon')
.next('td')
.invoke('text')
.then(lemonText => {
const lemonNumber = +lemonText.trim();
// do something with lemonNumber
})
Upvotes: 4
Reputation: 926
you can try this
cy.get('[data-id="77"] td:nth-child(2)').should('have.text', '77')
Upvotes: 0