I am pointing to the middle table cell and I can able to get text of the next cell using the next()
method but when I tried to use parent()
I am getting full row text which is three cells. Below is the HTML code. Kindly help.
cy.get('[name="courses"] > tbody >tr >td:nth-child(2)').each((e1, index) => {
const course = e1.text()
if (course.includes('Python')) {
cy.get('[name="courses"] > tbody >tr >td:nth-child(2)').eq(index).parent()
.then((price) => {
const courseprice = price.text()
// expect(courseprice).to.be.equal('25')
cy.log(courseprice)
})
}
})
5
Answers
The reason the text is the entire text is that it combines the text of all child elements. To avoid this, we can take a few different routes:
First solution: we can just check if the parent contains the value:
Second solution: grab the third row TD directly
After using
parent
, you can usewithin
to go inside the parenttr
and access eachtd
elements like this:You can reach the first
td
based on the secondtd
like this:It would be easier to iterate over the rows and check the 2nd instead of iterating over the 2nd and then travers up and down the DOM to get the price and then use
cypress-if
Here is a minimal reproducible example.
Another option, and my preferred way is to use
find
I would also recommend not usingthen
or or other nested function likeeach
if you don’t need it. And even though you can use jquery selectors likenth-child()
, using theeq()
makes it a bit more readable (IMHO). Alsonth-child
index is not 0-based but 1-based, sonth-child(2)
returns the 2nd column, not the 3rd.for example, this will give you the 8th row and 3rd column
if I repeat anything more than twice in a test, I tend to write helper functions in the spec.
in some cases, depending on your html markup, the text might be padded with white space. In that case you might want to use
contain.text
instead ofhave.text
but that could also cause issues, eg.125
would matchcontain.text("25")
.another option
Additionally, you can use
find
if you want to find a child element from a selector. In this case I added.find('td').eq(2)
. But note that this example shows a really convoluted way to search up and down the DOM.For the first row containing "Python",
.contains(selector, text)
is the shortest and.next()
gives you the price column.For multiple rows containing "Python", change to the pseudo-selector
:contains()