How to click a div with certain text in a nested div using cypress?

Viewed 1228

Below is my HTML code :

    <div class="main">
        <div class="box">
            <div class="cell">checkbox</div>
            <div class="cell"></div>
            <div class="cell">
                <a>link1</a>
            </div>
            <div class="cell">type</div>
            <div class="cell">description</div>
        </div>
        <div class="box"> //i want to click this element
            <div class="cell">checkbox</div>
            <div class="cell"></div>
            <div class="cell">
                <a>link2</a>
            </div>
            <div class="cell">type1</div>
            <div class="cell">description1</div>
        </div>
        <div class="box">
            <div class="cell">checkbox</div>
            <div class="cell"></div>
            <div class="cell">
                <a>link3</a>
            </div>
            <div class="cell">type2</div>
            <div class="cell">description2</div>
        </div>
    </div>

I'd like to click on the div with the class box containing the <a>link2</a> tag.

I have tried this :

    cy.get(`.main>div`).contains('link2').click();

This clicks on the link element itself, but I'd like it to click the div element that contains it (the <a>link2</a> tag) instead.

Is there any way to do this?
I'm looking forward to any tips and solutions you might provide.
Thanks.

2 Answers

You could try getting the link2's parent element which is the div you want to click, in the following way:

cy.get(`.main>div`).contains('link2').parent().click();

I believe you can use a selector in 'contains' itself like below

cy.contains('.main>div', 'link2').click();
Related