How to get text from an element in cypress

When working on automation with Cypress, we often need to fetch text from a webpage element.
Cypress provides several ways to do this:

  1. Using .invoke('text') after selecting an element with cy.get()
  2. Using jQuery methods inside a .then() callback
  3. Using .should() for text assertions without manually extracting text

Below are clean and correct examples demonstrating each approach.

✅ 1. Fetch Text Using invoke('text')

cy.get(‘css-selector’)
.invoke(‘text’)
.then((text) => {
cy.log(‘Fetched Text:’, text);
});

✅ 2. Fetch Text Using jQuery (.then() callback)

cy.get(‘css-selector’)
.then(($el) => {
const text = $el.text();
cy.log(‘Text from jQuery:’, text);
});

✅ 3. Fetch Text Using .should()

cy.get(‘css-selector’)
.should(‘have.text’, ‘Expected Text’);

If you need partial match:

cy.get(‘css-selector’)
.should(‘contain.text’, ‘Partial Text’);

✅ 4. Using Aliases to Re-use the Element Text

cy.get(‘css-selector’)
.invoke(‘text’)
.as(‘elementText’);

cy.get(‘@elementText’).then((text) => {
cy.log(‘Text from alias:’, text);
});

✅ 5. Fetching Text from Multiple Elements

cy.get(‘.items li’)
.then(($items) => {
const texts = […$items].map(el => el.innerText.trim());
cy.log(‘List of texts:’, JSON.stringify(texts));
});

✔ Summary

MethodBest ForExample
invoke('text')Text extraction.invoke('text')
jQuery (then)Advanced manipulation$el.text()
should()Assertion.should('contain.text', ...)
AliasesRe-use extracted text.as('name')
LoopsMultiple elementsMap through $elements
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Testingtalkslatest.com - A project by CreativeHub IT Solutions.
Contact Us At: support@testingtalkslatest.com
Our Partner websites - Classified Hub , CodesToolbox , Smart Fitness Guide , CodesToolbox , Testing Forum
Scroll to Top
0
Would love your thoughts, please comment.x
()
x