Reputation: 2433
In a Cypress test, I am trying to click a specific button nested inside a div, based on it's text.
Below is the HTML code I am testing:
<div class="mat-menu-content">
<button>First button</button>
<button>Second button</button>
</div>
I want to click the button with the Second button
text.
I can't just use cy.contains('Second button')
because Second Button
text appears multiple places on the page.
Here's what I'm trying to write using Cypress:
mat-menu-content
div that contains Second button
textCan someone please tell me how this can be done?
Upvotes: 0
Views: 1944
Reputation: 1422
Here's a single get
command that satisfies exactly what you want to do:
cy.get('div.mat-menu-content button:contains("Second button")'
Upvotes: 0
Reputation: 308
As you want to do 'Click the button inside mat-menu-content div that contains Second button text' i suggest
cy.get('div.mat-menu-content button').contains('Second button').click()
Upvotes: 0
Reputation: 853
If you have multiple menus on the page, the item buttons are only displayed when the menu is open, and only one menu will be open at a time.
You can go ahead and just select the button with the text Second button
after opening it's menu.
cy.contains('button', 'Contacts Menu').click() // open the menu
cy.contains('button', 'Second button').click() // select 2nd item
Upvotes: 3
Reputation: 18624
If you have multiple mat-menu-content
on the webpage you can use eq
to access a particular one and then use within()
to scope your query within div.mat-menu-content
cy.get('mat-menu-content')
.eq(0)
.within(() => {
//eq(0) points to the first occurance in the DOM
cy.contains('button', 'Second button').click()
})
Upvotes: 0
Reputation: 10550
One more variation, add .mat-menu-content
ahead of the button
selector
cy.contains('.mat-menu-content button', 'Second button') // tighter criteria
Upvotes: 0
Reputation: 2555
.contains()
is quite powerful and allows the use of a selector paired with text, cy.contains('selector', 'Your text')
.
For your scenario, you'll want to use the button
selector paired with the text to get the button containing Second button
.
cy.contains('button', 'Second button')
// or if there are multiple buttons with 'Second button' text on the page
cy.get('.mat-menu-content')
.contains('button', 'Second button')
.contains()
also allows for regex matching, which I prefer for finding with case insenstive.
cy.contains('button', /second button/i)
Upvotes: 1
Reputation: 1101
You should first grab the element by class name and then search for contents, and finally invoke the click() method. Try something like this:
cy.get('.mat-menu-content').contains('Second button').click()
For more info, look here in the official doc
Upvotes: 2