How to Get Text from List of Elements in Cypress

Related Product On This Page Setting up the Cypress Test Environment

June 17, 2026 · 11 min read · Tool Comparison
Related Product

How to Get Text from List of Elements in Cypress

In Cypress, extracting textbook from a tilt of elements is a common task in automation examination, allowing testers to control dynamic content and ensure the truth of UI element.

Overview

Getting Text in Cypress:

To efficaciously extract and validate schoolbook in Cypress, several commands and method can be used, depending on the scenario and the type of factor being targeted. Here ’ s how you can retrieve text in Cypress:

  • .text() Command:The .text () bid in Cypress is employ to recover the visible textbook from a selected element. It returns the combined text content of the ingredient and its shaver.
  • element and its kid..invoke (& # 8216; text & # 8217;): The .invoke (& # 8216; text & # 8217;) method is another way to get schoolbook from an element. It ’ s much used when you need to access a property of an ingredient.
  • Iterating Over Multiple Elements: When dealing with multiple elements (like a list of items), you can use .each () to iterate over them and retrieve the text of each.
  • Assertions: After extracting text, you can use Cypress assertions to compare it against expected values. You can check for exact match, partial matches, or insure the text is non-empty.

This article explores the BASIC of pull text in Cypress, while besides providing utile bakshis and good practices to enhance your examine process.

Setting up the Cypress Test Environment

Cypress is a -based application, so exploiter must feature Node.js installed on their systems. To get depart, the following requirement are necessitate:

Once finished, execute the following dictation to instal Cypress.

npm install cypress -- save-dev

The undermentioned command should be run after pilot to the undertaking directory if users want to install Cypress employ the Yarn software director:

yarn add cypress -- dev

Also Read:

Locating Elements on the Page

A locator is an identifier that apprise any mechanization tool in which GUI component (such as Text Boxes, Buttons, Check Boxes, etc.) are required for operation. The cy.get () method is used to obtain the.

There are numerous agency to site the elements:

  • Get HTML Element by ID Selector in Cypress
  • Get HTML constituent by Class in Cypress
  • Get HTML element by Tag Name in Cypress
  • Get HTML element by Attribute in Cypress
  • Working with Multiple Elements in Cypress
  • Useful Cypress Locator Functions
  • Get the HTML Element by XPath in Cypress

Read More:

Extracting Text from Elements

When trying to extract textbook from an HTML component, it is essential to have a fundamental understanding of how HTML element employment. Consider there are two key elements:

  • The & lt; div & gt; defines a section in an HTML papers.
  • The input element represents a typed datum field such as a countersign field.
& lt; div & gt; Please typewrite in your first gens: & lt; /div & gt; & lt; input type= '' schoolbook '' & gt; & lt; /input & gt;

During the test, fill in the input box and so ensure to see if the text has the right content. You can see the text on the page with both of these elements. However, if you want to & # 8220; assure text & # 8221; on each of these items, you must occupy a somewhat different approach:

cy .get ('div ') .should ('have.text ', 'Please type in your name: ')

For input field, you can no longer use the approaching you used to extract an component from a div. A different scheme is required. To typewrite into DOM factor in Cypress, use the type command. You must add that command here. Check below the latest version for the input field:

cy .get ('input ') .type ('Rick Sanchez ') .should ('have.value ', 'Rick Sanchez ')

The difference is that although the div ingredient convey a specific text, HTML comment elements are used to tuck values.

Read More:

Get attribute

Attributes can be used to set the HTML Element & # 8217; s place. They likewise help to define the behavior of the constituent when a sure requirement is met and triggered. There are attributes for virtually all HTML tags.

There may be times when you need to check your links. Then, it would be beneficial to obtain your href property from the lynchpin element. Suppose you have the next link:

& lt; a href= '' https: //www.browserstack.com/ '' & gt; App & amp; Browser Testing Made Easy! & lt; /a & gt;

You may create a tryout that seem like this to verify the href attribute:

cy .get (' a ') .invoke ('attr ', 'href ') .should ('eq ', 'https: //www.browserstack.com/ ')

Additionally, you may insure the validity of the link by sending an HTTP request to it:

cy .get (' a ') .invoke ('attr ', 'href ') .then (href = & gt; {cy .request (href) .its ('status ') .should ('eq ', 200);});

Text Validations in Cypress

Cypress uses the jQuery text () method to validate text on an ingredient. The text content of the chosen element will be find using this approach. Moreover, you can create assertion on the element & # 8217; s text message.

cy.get ('.product ') .should ('have.text ', Browserstack);

With the support of the Javascript methods match (), include (), and others, you may execute substantiation on the text, such as confirming its contents or fit requirements. As a solution, jQuery objects may be used by Cypress commands to interact with non-Cypress methods and invoke method on them.

Under the hood, elem.textContent is automatically called by jQuery & # 8217; s.text () function. You can choose to employ innerText as an option by doing the following:

cy.get ('div ') .should (($ div) = & gt; {// access the native DOM element expect ($ div.get (0) .innerText) .to.eq ('foobarbaz ')})

For autonomous testing across multiple user personas, check out SUSATest — it explores your app like 10 different real users.

Array vs jQuery object

& lt; div & gt; & lt; div & gt; first & lt; /div & gt; & lt; div & gt; second & lt; /div & gt; & lt; div & gt; third & lt; /div & gt; & lt; div & gt; quaternary & lt; /div & gt; & lt; div & gt; fifth & lt; /div & gt; & lt; /div & gt;
cy.get ('.matching ') .then (($ els) = & gt; {expect (Cypress.dom.isJquery ($ els), 'jQuery object ') .to.be .true const component = Cypress. $ .makeArray ($ els) expect (Cypress.dom.isJquery (elements), 'converted ') .to.be .false expect (elements, 'to array ') .to.be.an ('array ') homecoming component}) .then ((x) = & gt; {// but get rearward a jQuery object again expect (Cypress.dom.isJquery (x), 'back to jQuery object ') .to .be.true anticipate (x, 'an not a raiment ') .to.not.be.an ('array ') anticipate (x.length, ' 3 elements ') .to.equal (3)})
& lt; ul & gt; & lt; li & gt; A & lt; /li & gt; & lt; li & gt; B & lt; /li & gt; & lt; li & gt; C & lt; /li & gt; & lt; li & gt; D & lt; /li & gt; & lt; /div & gt;
cy.get (' # item li ') .each (($ li) = & gt; cy.log ($ li.text ()))
//Collect the items then print const items = [] cy.get (' # items li ') .each (($ li) = & gt; items.push ($ li.text ())) .then (() = & gt; {cy.log (items.join (', '))})
//Collect the items then assert the inclination const items = [] cy.get (' # items li ') .each (($ li) = & gt; items.push ($ li.text ())) // the item reference is set once cy.wrap (items) .should ('deep.equal ', [' A ', ' B ', ' C ', 'D ',])

How to find text using contains () command

Using Cypress contains command, you may find the DOM element that hold the text. CSS selectors may make it gainsay to place the element by text, but Cypress offers a solution. You should be capable to get the element by expend the contains () purpose along with the tag name. In the event that more than one DOM element contains the necessary text, the first one will be match. One of the near used bidding in Cypress is .contains (). While sounding like an assertion in its name, this command is actually a selecting command. For contains command documentation, pawlhere.

Read More:

Contains with twine content

cy.contains (`` Forms '') .click ();

contains with number content

cy.contains (2023);

contains with get ()

cy.get (`` span.menu-title '') .contains (`` layouts '') .click ();

contains with selector and message

cy.contains (`` span.menu-title '', '' layouts '') .click ();

Using invoke () to call a function:

Since Cypress commands do not really execute synchronously, they foremost check to see if the factor specified by that selector is available or not. so you must use the .invoke () function to await until the factor becomes available. Clickhereto apprehend it more:

const obj = {getNumber: () = & gt; {return 10;}}; cy.wrap (obj) .invoke ('getNumber ') .should ('eq ', 10);

If you ask more, further statement may be added to the map:

const obj = {sum: function (a, b) {return a + b}}; cy.wrap (obj) .invoke ('sum ', 2, 3) .should ('eq ', 5);

Like what you are reading?

You can get discussing with our discord community

Taking attributes off of HTML elements

Text can be taken out of an HTML element. Consider the next h1 element:

& lt; h1 & gt; Cypress essay & lt; /h1 & gt;

After that, you can confirm the text it contains:

cy.get ('h1 ') .invoke ('text ') .should ('contain ', 'testing ');

Using the undermentioned code, you might affirm if an image & # 8217; s src property points to the right url:

cy.get ('img ') .eq (0) .invoke ('attr ', 'src ') .then ((src) = & gt; {cy.request (src) .then ((resp) = & gt; {cy.wrap (resp.status) .should ('eq ', 200);})});

Extract a select & # 8217; s option inclination:

cy.get ('.multiple-select ') .invoke ('val ') .should ('include ', 'option1 ')

If the mantled object lack a function, you can extract a property by using & # 8220; its & # 8221; rather than & # 8220; invoke & # 8221;:

const obj = {value: 23}; cy.wrap (obj) .invoke ('value ') .should ('eq ', 23); // This execute not work! cy.wrap (obj) .its ('value ') .should ('eq ', 23);

Here are the ways that may be used to obtain a Cypress element & # 8217; s text so that it can be utilized for text assertion:

You may maintain the value as an alias and utilise that alias for future reference by using Alias= & gt; .as (). In Cypress, the Alias is saved apply the & # 8220; .as () & # 8221; function.

  • Invoke-Command and Alias: You will call cy.get (locator). invoke (& # 8216; text & # 8217;), so use an alias = & gt; textFunction to save the value of textbook so that it may be printed expend this.aliasName in the next function.
  • Using the Wrap Command with Alias: This technique regard wrapping the textbook & # 8217; s value in an alias = & gt; textvalue before print it using this.aliasName in the second function.
  • Using the Variables: In addition to using an alias, You may store text values in variables and utilize those variable in multiple purpose.

Talk to an Expert

Cypress Selector Playground

Another helpful lineament offered by Cypress for users is the ability to cursorily notice on pages right from the test moon-curser. To avoid trouble while using component, Selector Playground will always match and discover their unique locators.

The primacy of the distinctive locator that Cypress supports is displayed below:

  • data-cy
  • data-test
  • data-testid
  • id
  • class
  • tag
  • attributes
  • nth-child

Read More:

The WebElements should have the Cypress-recommended attributes data- * bestow to them in order to protect them from JS/CSS changes that would cause the test to fail.

Talk to an Expert

Custom Cypress Commands

Use the data-test attribute like so:

cy.get (`` [data-test='hero-heading '] '')

Even if this is true, wouldn & # 8217; t it be howling if you could simplify this syntax to create our tests simpler to write, interpret, and analyze?

You can create our own uniqueCypress biddingto do this. you can recycle code or functionality across all of our Cypress spec files thanks to a custom command.

To better & # 8220; obtain & # 8221; data-test attribute for our use case, you wish to develop a custom Cypress command. This requires that you qualify the cypress/support/commands.ts file to include our new command.

This file will by default include a good amount of comments in the code that explain how to write a custom bidding. This file should be updated to the following and all code comments should be removed:

/// & lt; reference types= '' cypress '' / & gt; Cypress.Commands.add (`` getByData '', (selector) = & gt; {return cy.get (` [data-test= $ {selector}] `)})

Note: You could see compiler job stating that it was unable to recognize the case in our tradition dictation since you are using TypeScript. You may objurgate this by do the following additions to the file cypress/support/index.ts:

/// & lt; reference types= '' cypress '' / & gt; declare namespace Cypress {interface Chainable {getByData (dataTestAttribute: string): Chainable & lt; JQuery & lt; HTMLElement & gt; & gt;}}

Now the usance bidding is ready and you will see here how to implement your tradition command in place of the cypress command in the example given below:

You can only afford the value of any data-test belongings into this custom command name & # 8220; getByData, & # 8221; like in the following example:

cy.getByData (`` hero-heading '')

instead of:

cy.get (`` [data-test='hero-heading '] '')

After develop our customs command, let & # 8217; s refactor our cypress/e2e/home.cy.ts tryout to create use of it and verify that our exam is still passing.

// home.cy.ts it (`` the h1 moderate the correct text '', () = & gt; {cy.getByData (`` hero-heading '') .contains ('' Testing Next.js Applications with Cypress '')})

Conclusion

When testing Cypress, typical issues arise, and if you carefully heed the preceding guidance, your unremarkable operation should be error-free.

Note that for true results, needs to be run on actual browsers. Start using BrowserStack to conduct examination on more than 30 edition of the latest browsers on Windows and macOS.

Use quick, painless Cypress parallelization to run and get faster results without sacrificing truth. In order to find bugs before user do, applications must be tested using BrowserStack in.

Tags
91,000+ Views

# Ask-and-Contributeabout this topic with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free