Cypress: select outer element with cy.contains()

Created on 27 Jul 2018  路  6Comments  路  Source: cypress-io/cypress

Current behavior:

As you mentioned below we can reach an element with html tags:

https://docs.cypress.io/api/commands/contains.html#Selector

But if a tag name is exists more than one nested it select the innermost one.

screen shot 2018-07-27 at 12 57 32

Test code is below:

cy.contains('tr', 'Semanta Murphy')

Desired behavior:

But i need outer DOM object. How can I select it?

Versions


Cypress 3.0.2
macOS 10
Electron 59

question

Most helpful comment

Yes, this is the intended behavior of .contains() when passed a selector - to find the deepest element containing the text, then go up to the first parent matching the selector passed.

Some things that would get you the tr's parent tr:

cy.contains('tr', 'Semanta Murphy').parent('td').parent('tr')
cy.contains('tr', 'Semanta Murphy').parentsUntil('tr')
cy.contains('tr.ember-view', 'Semanta Murphy')

Let me know if this helps.

All 6 comments

Yes, this is the intended behavior of .contains() when passed a selector - to find the deepest element containing the text, then go up to the first parent matching the selector passed.

Some things that would get you the tr's parent tr:

cy.contains('tr', 'Semanta Murphy').parent('td').parent('tr')
cy.contains('tr', 'Semanta Murphy').parentsUntil('tr')
cy.contains('tr.ember-view', 'Semanta Murphy')

Let me know if this helps.

Hi @jennifer-shehane
Thank you for answer. Here is the results;

cy.contains('tr', 'Semanta Murphy').parent('td').parent('tr')

worked fine :)

cy.contains('tr', 'Semanta Murphy').parentsUntil('tr')

not worked. Found the same deepest element :(

cy.contains('tr.ember-view', 'Semanta Murphy')

worked fine :)

Best,

Oh no, yeah, I should always try the code before typing it out. 馃槃 Thanks for posting your results.

I tried parentsUntil('some-top-element'), and it worked as documented. The subtle thing I missed at first was this part of the doc:

up to but not including the element matched by the selector

So in the context of this question, I believe

cy.contains('tr', 'Semanta Murphy').parentsUntil('tbody').last()

should yield the desired element.

The traversal commands ie: parent and parentsUntil match their jquery counterparts so you can always look at the equivalent jquery command (if one exists) like here:

Also parentsUntil(null, 'tr.ember-view') worked for me. Second parameter is a filter, so if you have a selector which safely matches a single level, it's fine.

A cy.safeContains() command can be implemented this way:

Cypress.Commands.add('safeContains', (collectionSelector, searchSelector, searchString) => cy
    .get(collectionSelector)
    .contains(searchSelector, searchString)
    .parentsUntil(null, collectionSelector));

cy.safeContains('tr', 'td.name', 'foo') then returns a tr element which has the 'foo' match in his name column.

Was this page helpful?
0 / 5 - 0 ratings