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
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. Locators supported by Cypress Working with Multiple Elements in Cypress You can start discussing with our discordance community Useful Cypress Locator Functions 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. 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 To get the HTML element by id in Cypress, use the following dictation: 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: In the above example, inputmyid98788is entered in the HTML element with IDuser_email_login. 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 To get the HTML factor by id in Cypress, use the following command: In this bid,. (dot)is used as a prefix to class insidecy.get() 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 To get the HTML element by Tag gens in Cypress, use the following command: 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 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: 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. The below example demonstrates Cypress Locators with actions: 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 Whereas, to get the password textbox element using the CSS attribute locators and typecast the password & # 8220;Mypassword123& # 8220;, the following line is used. Then snap on Submit button using the following command The chase is the Assertion for Error Message: Cypress CSS selector with Regular Expression (RegEx) Patterns Cypress too indorse CSS regular expression pattern inside thecy.get() function 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(). 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: 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. Alike to the above illustration, here.last()function is used to get the last element in a set of component For Example: 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. 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) 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 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. 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 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 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. 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 _) To ignore the Case Sensitivity while using regular expressions insidecontains ()function, use{matchCase: mistaken} To get the descended DOM element of a specific locator, usecy.find()office as seen in the representative below: For HTML Code The following dictation homecoming all ordered list (li) constituent inside the ungraded lean (ul) element cy.get (& # 8216; # parent & # 8217;) .find (& # 8216; li & # 8217;) The .next()function returns the next sibling in Cypress as seen below While, to get the next sib which is an input tag, use the following command: The .prev()purpose revert the previous sib in Cypress as seen below While, to get the previous sibling which is an input tag, use the following command: The .nextAll ()office returns the next sibling in Cypress as witness below The .prevAll ()function returns the late sib in Cypress as seen below The .siblings ()function is used to find the siblings in Cypress as seen below Or 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: Similarly, to get previous sibling element until the element class name is& # 8216; my_class_name & # 8217;, use the command as seen below: The .within()role scopes all subsequent cy commands within this element as seen in the example below: For HTML Code 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, 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: Step 2:Set Up XPath plugin Navigate tocypress/support/index.jsand add the below line Step 3: Use cy.xpath ()command in the script as seen in the example below To get specific factor using XPath you can also chain thecy.xpath ()to another command as seen below 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 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. Step 5:Execute your BrowserStack Test by using the below bidding 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. On This Page # Ask-and-Contributeabout this topic with our Discord community. Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed. Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.Cypress Locators: How to find HTML element
Overview
Like what you are reading?
Get HTML Element by ID Selector in Cypress
& lt; input & gt;
cy.get (' # user_email_login ')cy.get (' # user_email_login ') .type ('myid98788 ');Get HTML factor by Class in Cypress
& lt; input & gt;
cy.get ('.user_email_ajax ')Get HTML element by Tag Name in Cypress
& lt; stimulus & gt;
cy.get ('input ')Get HTML element by Attribute in Cypress
& lt; input type= '' schoolbook '' name= '' user_login '' & gt;
cy.get ('input [name= '' user_login ''] ')cy.get ('input [id= '' user_email_login ''] ')cy.get ('input [class= '' user_email ''] ')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 ');})})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 password ');Symbol Description Example /Usage * Match all element that curb the value cy.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 value cy.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 value cy.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
cy.get ('.msg-body ') .first ()cy.get ('.msg-body ') .last ()For Example: cy.get (' a: contains (`` Forgot passoword '') ') .first () .click ()cy.contains ('Sign In ');cy.get (' a ') .contains ('Sign In ');cy.contains (/^b\w+/)
cy.get ('div ') .contains ('capital condemnation ', {matchCase: mistaken})& lt; ul & gt; & lt; li & gt; & lt; /li & gt; & lt; li & gt; & lt; /li & gt; & lt; /ul & gt;
Utilitarian Cypress Locator Functions
cy.get (' # my_ele ') .next ();cy.get (' # my_ele ') .next ('input ');cy.get (' # my_ele ') .prev ();cy.get (' # my_ele ') .prev ('input ');cy.get (' # my_ele ') .nextAll ();cy.get (' # my_ele ') .prevAll ();cy.get ('li ') .siblings ('.active ')cy.get ('li ') .siblings ()cy.get ('li ') .nextUntil ('.my_class_name ')cy.get ('li ') .prevUntil ('.my_class_name ')& 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;
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
npm install -D cypress-xpath
require ('cypress-xpath ')it ('finds list items ', () = & gt; {cy.xpath ('//ul [@ class= '' todo-list ''] //li ') .should ('have.length ', 3)})it ('finds list items ', () = & gt; {cy.xpath ('//ul [@ class= '' todo-list ''] ') .xpath ('./li ') .should ('have.length ', 3)})Executing Cypress Test Scripts habituate Browserstack
{'' 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 '',}}{'' testFiles '': [`` * .js '']}browserstack-cypress run –sync
Related Guides
Automate This With SUSA
Test Your App Autonomously