Cypress技术问询:如何根据文本从元素列表定位并点击元素
How to Find & Click an Element by Text in a List with Cypress
Hey there! Let's get your Cypress test working to target that specific element by its text. First, let's break down the issues in your current code:
- No need to call
cy.get($elm)again inside the.each()callback—$elmis already a jQuery object for the current element in the loop. - You can't chain
.click()right after anexpect()assertion; assertions are synchronous and don't return a Cypress command chain to keep building on. - When you find the matching text, you need to click the actual element (not the assertion result!).
Fixed Version Using .each()
Here's the corrected code that will loop through your elements, find the one with your target text, and click it:
cy.get('partie-room-list-item > div > div.content-block > span.partie-title').each(($elm, index) => { const elementText = $elm.text().trim(); // Trim whitespace to avoid accidental mismatches if (elementText === 'textinelement') { cy.wrap($elm).click(); // Wrap the jQuery object to use Cypress's click command cy.log(`Successfully clicked element with text: ${elementText}`); return false; // Exit the loop early once we find our target—no need to keep checking! } });
A Cleaner, More Cypress-Native Approach
Cypress has a built-in .contains() command that simplifies this workflow a ton. Instead of looping manually, you can directly target the element with your text like this:
// This directly finds the span with exactly "textinelement" and clicks it cy.get('partie-room-list-item > div > div.content-block') .contains('span.partie-title', 'textinelement', { matchCase: true }) .click();
- The
{ matchCase: true }flag makes sure the text match is case-sensitive (this is the default, but spelling it out makes your intent clear). - If you need to ignore extra whitespace in the element's text, use a regex instead:
.contains('span.partie-title', /^textinelement$/)
Quick Tips
- Always trim text when comparing—elements often have hidden whitespace that can break your matches.
- Adding
return falsein the.each()loop stops the iteration as soon as you find your element, which is more efficient. .contains()is usually the best choice for text-based selection in Cypress—it's more readable and leverages the framework's built-in logic.
内容的提问来源于stack exchange,提问作者Kashif nadeem
相关产品推荐
相关产品推荐

