Cypress Locators : How to find HTML elements

On This Page Get HTML Element by ID Selector in CypressMay 24, 2026 · 12 min read · Tool Comparison

Cypress Locators: How to find HTML element

A Selector or Locator is an object that encounter and render web page items/elements on a page based on the question. In Automation, to perform any operation on the web elements first, you involve to locate an ingredient and perform an action on it.

supports various locators such as tags, id, class, attributes, text, etc. Cypress too back XPath Selectors; nonetheless, it needs installation of the third-party plugincypress-xpath.

Overview

Locators supported by Cypress

  • ID selectors (e.g. cy.get (& # 8216; # idName & # 8217;))
  • Class, tag name, attribute selectors via CSS selectors
  • Text-based locators utilize .contains ()
  • XPath via cypress-xpath plugin

Working with Multiple Elements in Cypress

  • cy.get () will Locate elements using CSS selectors.
  • Use .first (), .last (), and .eq (n) to pick specific elements from a set.
  • cy.contains () will find constituent with matching text.
  • cy.find () will specialize search to descendants of a selected element.

Like what you are reading?

You can start discussing with our discordance community

Useful Cypress Locator Functions

  • .next (), .nextAll (), .nextUntil () functions returns the next sibling/siblings in order
  • .prev (), .prevAll (), .prevUntil () functions render the late sibling/siblings in order
  • .within () require scopes all subsequent Cypress commands to within a specific element.

This article research the various locators endorse by Cypress such as ID, family, tag name, attributes and more. It also cover how to execute Cypress tests on BrowserStack.

Get HTML Element by ID Selector in Cypress

IDis an dimension of an HTML tag, which is used to find an HTML element. Using the Cypress command & # 8211;cy.get(), you can directly surpass the id with prefix#and get the element.

Let & # 8217; s see this using an example:

Consider code for an HTML element withid name user_email_login and class name user_email_ajax

& lt; input & gt;

To get the HTML element by id in Cypress, use the following dictation:

cy.get (' # user_email_login ')

In this command,#is used as a prefix to id insidecy.get()

Once you are able to regain the HTML element, you can perform operations on the elements such astype, click, etc., as seen in the example below:

cy.get (' # user_email_login ') .type ('myid98788 ');

In the above example, inputmyid98788is entered in the HTML element with IDuser_email_login.

Get HTML factor by Class in Cypress

Just like ID, Classis also an attribute of an HTML element, that is use as a locater or selector. Alike to how ID is directly passed with a prefix#using the Cypress commandcy.get(), classcan too be used to get the HTML element with. (dot)as a prefix insidecy.get().

For example, consider code for an HTML component withclass name user_email_ajax

& lt; input & gt;

To get the HTML factor by id in Cypress, use the following command:

cy.get ('.user_email_ajax ')

In this bid,. (dot)is used as a prefix to class insidecy.get()

Get HTML element by Tag Name in Cypress

Using the Cypress command & # 8211;cy.get(), you can directly get the component by legislate the tag name.

Consider code for an HTML ingredient withtag name input

& lt; stimulus & gt;

To get the HTML element by Tag gens in Cypress, use the following command:

cy.get ('input ')

Get HTML element by Attribute in Cypress

Cypress cater a way to get the element by attribute gens. Since it endorse all the different types of CSS selectors, you can pass the CSS selectors inside thecy.get()command to get an element.

Let & # 8217; s understand this using an example:

Consider codification for an HTML element withid name user_email_login and class name user_email_ajax

& lt; input type= '' schoolbook '' name= '' user_login '' & gt;

In the above code, there is an dimension calledname. To get an element use an attribute in Cypress, you can simply pass CSS selector tocy.get() as seen below:

cy.get ('input [name= '' user_login ''] ')

However, id and class are also attribute. So, instead of using#, or . (dot)prefix, you can also get the component by utilize ID name or Class name by apply ID and category as attributes.

  • Get element by ID using id as an attribute
cy.get ('input [id= '' user_email_login ''] ')
  • Get element by class name using class as an dimension
cy.get ('input [class= '' user_email ''] ')

The below example demonstrates Cypress Locators with actions:

describe ('Cypress Locators Demo ', () = & gt; {it ('Verify Error Message ', () = & gt; {cy.visit (`` https: //www.browserstack.com/users/sign_in ''); cy.get (' # user_email_login ') .type ('example @ example.com ') cy.get ('input [id= '' user_password ''] ') .type ('Mypassword123 ') cy.get (' # user_submit ') .click (); cy.get ('.pass-input-placeholder & gt; .input-wrapper & gt; .error-msg & gt; .msg-body & gt; span ') .should ('contain.text ', 'Invalid watchword ');})})

The above code navigates to the Browserstack Sign-in page and gets relevant locators. The following line gets an email textbox element withIDlocator and allows the user to typecast the e-mail address & # 8220;example @ example.com& # 8221; in it

cy.get (' # user_email_login ') .type ('example @ example.com ')

Whereas, to get the password textbox element using the CSS attribute locators and typecast the password & # 8220;Mypassword123& # 8220;, the following line is used.

cy.get ('input [id= '' user_password ''] ') .type ('Mypassword123 ')

Then snap on Submit button using the following command

cy.get (' # user_submit ') .click ();

The chase is the Assertion for Error Message:

cy.get ('.pass-input-placeholder & gt; .input-wrapper & gt; .error-msg & gt; .msg-body & gt; span ') .should ('contain.text ', 'Invalid password ');

Cypress CSS selector with Regular Expression (RegEx) Patterns

Cypress too indorse CSS regular expression pattern inside thecy.get() function

SymbolDescriptionExample /Usage
*Match all element that curb the valuecy.get (& # 8216; [class * = & # 8221; react-class & # 8221;] & # 8217;): Matches all class element which contains the family name “ react-class ”
$Match all element that cease with the valuecy.get (& # 8216; [class $ = & # 8221; react-class & # 8221;] & # 8217;): Matches all class component which stop with the class gens “ react-class ”
^Match all factor that get with the valuecy.get (& # 8216; [class^= & # 8221; react-class & # 8221;] & # 8217;): Matches all class factor which starts with the class name “ react-class ”

Working with Multiple Elements in Cypress

When using thecy.get()purpose to fetch single or multiple factor, in suit there are multiple matches,cy.get()return all of them. Considering that you have to work with the first element, last element, or element at a specific index, then you want to use thefirst(), last(), or eq()role along withcy.get().

  • Get the first Element in Cypress
  • For autonomous testing across multiple user personas, check out SUSATest — it explores your app like 10 different real users.

The function .first()is habituate to get the first constituent in a set of elements

For Example:

cy.get ('.msg-body ') .first ()

In the above example, the commandcy.get (& # 8216; .msg-body & # 8217;)might return more than one element, but by applyfirst()it will constantly the first element within the set of the elements fetch.

  • Get the last Element in Cypress

Alike to the above illustration, here.last()function is used to get the last element in a set of component

For Example:

cy.get ('.msg-body ') .last ()

In the above example, the commandcy.get (& # 8216; .msg-body & # 8217;)might return more than one element, but by usinglast()it will always be the last element within the set of the elements fetched.

  • Get the specific element by index in Cypress

To get a specific element in the set of elements, usingeq()function along withcy.get (& # 8216; .msg-body & # 8217;)as exhibit below

cy.get (& # 8216; .msg-body & # 8217;) .eq (2)

  • Get Element By Containing Text in Cypress

It might be hard to find the element by text using, but Cypress provides a way to do that. You can but use thecontains ()function along with the tag name and should be able to get the constituent.

The above approaching is most useful to find thehref linkby Text in Cypress

For Example: cy.get (' a: contains (`` Forgot passoword '') ') .first () .click ()

Note:The above model we are apply contains () for & lt; a & gt; component, but you can use it for any element if you want to find the attribute or perform an activeness using text. There are other approaches discussed below.

  • Get DOM Element contain Text in Cypress

Cypress plycontains ()function, which can be used withcycommand or can be chain withcy.get()command to get the DOM ingredient as understand in the instance below

Example 1:

Find the element get Text Sign In

cy.contains ('Sign In ');

The above command searches forText ‘ Sign In ’inside the web page and returns the element. However, the command doesn ’ t tab which type of element it is.

Example 2:

Find the DOM element having Text Sign In

cy.get (' a ') .contains ('Sign In ');

The above command hunt for all<a>tags and render the Element if<a>is having text‘Sign In’. So, considering the 1st example, this attack is more specific to the tag name.

  • Using Regular expressions inside the cy.contains ()

Cypress allows the use of regular reflection insidecontains ()function. As seen in the below example, you can search for the constituent containing text that begin with b and has one or more word characters(figure, alphabet, and _)

cy.contains (/^b\w+/)

To ignore the Case Sensitivity while using regular expressions insidecontains ()function, use{matchCase: mistaken}

cy.get ('div ') .contains ('capital condemnation ', {matchCase: mistaken})
  • Get the descendent DOM elements of a specific selector

To get the descended DOM element of a specific locator, usecy.find()office as seen in the representative below:

For HTML Code

& lt; ul & gt; & lt; li & gt; & lt; /li & gt; & lt; li & gt; & lt; /li & gt; & lt; /ul & gt;

The following dictation homecoming all ordered list (li) constituent inside the ungraded lean (ul) element

cy.get (& # 8216; # parent & # 8217;) .find (& # 8216; li & # 8217;)

Utilitarian Cypress Locator Functions

  • Get the Adjacent Sibling in Cypress

The .next()function returns the next sibling in Cypress as seen below

cy.get (' # my_ele ') .next ();

While, to get the next sib which is an input tag, use the following command:

cy.get (' # my_ele ') .next ('input ');
  • Get the Previous Sibling in Cypress

The .prev()purpose revert the previous sib in Cypress as seen below

cy.get (' # my_ele ') .prev ();

While, to get the previous sibling which is an input tag, use the following command:

cy.get (' # my_ele ') .prev ('input ');
  • Get All Future Siblings in Cypress

The .nextAll ()office returns the next sibling in Cypress as witness below

cy.get (' # my_ele ') .nextAll ();
  • Get All Previous Sibling in Cypress

The .prevAll ()function returns the late sib in Cypress as seen below

cy.get (' # my_ele ') .prevAll ();
  • Get Any Siblings

The .siblings ()function is used to find the siblings in Cypress as seen below

cy.get ('li ') .siblings ('.active ')

Or

cy.get ('li ') .siblings ()
  • Get The Siblings Until in Cypress

The functions.nextUntil ()and .prevUntil ()allows you to get all the siblings before or after a certain condition. For example, to get all the next sibling elements until the element class gens is& # 8216; my_class_name & # 8217;, use the command as realize below:

cy.get ('li ') .nextUntil ('.my_class_name ')

Similarly, to get previous sibling element until the element class name is& # 8216; my_class_name & # 8217;, use the command as seen below:

cy.get ('li ') .prevUntil ('.my_class_name ')
  • Within Command in Cypress

The .within()role scopes all subsequent cy commands within this element as seen in the example below:

For HTML Code

& lt; descriptor & gt; & lt; input name= '' email '' type= '' email '' & gt; & lt; input name= '' password '' type= '' word '' & gt; & lt; button type= '' submit '' & gt; Login & lt; /button & gt; & lt; /form & gt;

The following bidding will search for the elements only within the form, instead of searching the unharmed code, and returns only the relevant constituent within the form,

cy.get ('form ') .within (($ form) = & gt; {// cy.get () will only search for elements within form, // not within the entire document cy.get ('input [name= '' e-mail ''] ') .type ('eaxample @ email.com ') cy.get ('input [name= '' password ''] ') .type ('mypassword ') cy.root () .submit ()})

Get the HTML Element by XPath in Cypress

As mentioned earlier Cypress doesn ’ t support XPath out of the box, however, if you are already conversant with XPath then you can use the third-party plugincypress-xpathto get the HTML element by XPath by using the next stairs:

Step 1:Install thecypress-xpathplugin using the below command:

npm install -D cypress-xpath

Step 2:Set Up XPath plugin

Navigate tocypress/support/index.jsand add the below line

require ('cypress-xpath ')

Step 3: Use cy.xpath ()command in the script as seen in the example below

it ('finds list items ', () = & gt; {cy.xpath ('//ul [@ class= '' todo-list ''] //li ') .should ('have.length ', 3)})

To get specific factor using XPath you can also chain thecy.xpath ()to another command as seen below

it ('finds list items ', () = & gt; {cy.xpath ('//ul [@ class= '' todo-list ''] ') .xpath ('./li ') .should ('have.length ', 3)})

Executing Cypress Test Scripts habituate Browserstack

BrowserStack permit you to fulfill your Cypress test scripts or specs on multiple platforms and multiple browser versions. Interestingly you do not experience to change Cypress specs, all you have to do is a simple configuration set up as shown in the next measure:

Step 1: Install

Step 2: Create a browserstack.jsonfile using thebrowserstack-cypress init command

Step 3:Enter the below code to thebrowserstack.json file

{'' auth '': {'' username '': `` & lt; my_username & gt; '', '' access_key '': `` & lt; my_access_key & gt; ''}, '' browsers '': [{'' browser '': `` chrome '', '' os '': `` Windows 10 '', '' versions '': ['' latest '', '' up-to-the-minute - 1 '']}], '' run_settings '': {'' cypress_config_file '': `` ./cypress.json '', '' cypress_version '': `` 9 '', '' project_name '': `` My sandpit undertaking '', '' build_name '': `` Build no. 1 '', '' parallels '': `` 2 '',}}

Note:You can observe the username and access key by logging into the BrowserStack website. You can too modify the browser settings and platform settings from thebrowserstack.json file

Step 4:Configure thecypress.jsonfile to include the.js files.

{'' testFiles '': [`` * .js '']}

Step 5:Execute your BrowserStack Test by using the below bidding

browserstack-cypress run –sync

Bear in psyche that must be executed on existent browser for accurate results. Start running tests on 30+ versions of the up-to-the-minute browsers across Windows and macOS with BrowserStack. Use instant, hassle-free Cypress parallelization to and get fast resolution without compromising on accuracy. Detect bugs before users do by examine software in with BrowserStack.

Tags
13,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