2

Can someone please assist in following case:

I have to check in if statement does element exist. Since there is no possibility to use Xpath in find command (Throws Syntax error when run it with Xpath).

My code looks:

cy.xpath(list)
    .eq(index)
    .then(($el1) => {
      cy.get('body').then((body) => {
        if (
          body.find(
            currentBase +
              currentTitle[index] +
              currentExtension
          ).length > 0
        ) {
     ...

Where currentBase is Xpath before text, currentText - element with text and currentExtension is concatentation to get element below that text element. I do not want to use those classes since they are dynamic ones (also, can not be changed with some unique attribute in near future)

And DOM looks:

enter image description here

Namely, easily is found marked img element, but with following CSS, it does not work

#structures img[src*="/static/media/image"].$('..').$('..').$('..') div:nth-child(2)

What I want is, to find div below element with text Element One

What I am doing wrong? Or is there any other way in Cypress to use together if statement and to pass that step if element is not found? Thank you in advance

Zoran
  • 491
  • 7
  • 22

1 Answers1

2

You can do something like this. This will get you the div element just below Element One and which is also the parent element for the img

cy.get('img[src*="/static/media/image"]').parent('div')
Alapan Das
  • 17,144
  • 3
  • 29
  • 52
  • It does work. Thank you very much @Alapan Das – Zoran Nov 23 '21 at 10:25
  • 1
    Yes, just have to wait few minutes, already tried – Zoran Nov 23 '21 at 10:27
  • @Alapan Just to understand. I see here https://stackoverflow.com/questions/1014861/is-there-a-css-parent-selector and in other places that there is not way to go up to a parent element with CSS selectors. What is the difference? – Prophet Nov 23 '21 at 10:33
  • 1
    Not sure I understand your question, but you can read this https://docs.cypress.io/api/commands/parent. `parent` is a cypress command, that is designed to do specifically the task you were looking for. If you want to learn more about it, I have written a blog on this topic which you can also look at, if you would be interested - https://testersdock.com/cypress-parents-parent-children/ – Alapan Das Nov 23 '21 at 10:36
  • Ah, OK, I see. No, I do not have any relation to cypress, making automation mostly with Java and Python. I thought there is a way to do such CSS Selector. As I know it's impossible. – Prophet Nov 23 '21 at 10:42