How to get text of an element in Cypress

Last updated on Mar 5, 2023 by Suraj Sharma



In this tutorial, you will learn how you can use the .text() method in Cypress to get the text content of an element.


Example:


// select the element and get its text content
  cy.get('.content').text().then((text) => {
    // use the text in your test
    expect(text).to.equal('Hello, World!');
  });


In this example, we're selecting an element with the class name .content and using the .text() command to get its text content.


You can also use the .invoke() command to retrieve the value of any property of an element, including its text content.


Example:


  cy.get('.my-element').invoke('text').then((text) => {
    // use the text in your test
    expect(text).to.equal('Hello, World!');
  });


In this example, we're using the .invoke() command to retrieve the text property of the selected element, which contains its text content.



Related Solutions


Rate this post


Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.