04 Element Locators - biswajitsundara/Cypress GitHub Wiki

Cypress uses only CSS selectors and has some inbuilt methods that helps in identifying elements on a webpage.

CSS Selectors

1. Select elements by ID

   Synatx: #id
   Desc: Selects all elements having the id
   DOM: <input id="email" class="form-control form-control-lg" placeholder="Email">
   Selector: #email
   Example: cy.get('#email').type('biswajit'); 

We can also use tagname#id. Example here = input#email

2. Select elements by Class name

   Synatx: .class
   Desc: Selects all elements with class="intro"
   DOM: <input id="email" class="username" placeholder="Email">
   Selector: .username
   Example: cy.get('.username').type('biswajit'); 

We can also use tagname.classname Example here = input.username

3. Select elements by attribute

   Synatx: [attribute=value]
   Desc: Selects all elements with attribute="value"
   DOM: <input type="email" class="form-control form-control-lg" placeholder="Email">
   Selector: [type="email"]
   Example: cy.get('[type="email"]').type('biswajit'); 

We can also use tagname[attribute=value] . Example here = input[type="email"]

4. Select enabled elements

   Synatx: [tagname:enabled]
   Desc: Selects every enabled  element
   DOM: <input type="email" class="form-control form-control-lg" placeholder="Email">
   Selector: input:enabled
   Example: cy.get('input:enabled').get('input[type="email"]').type("sundara");

5. Select child elements

   Synatx: parenttagname childtagname (there's a space in between) 
   Desc: Selects all children under the parent tag. Let's say we have a form and under that input elements.
   DOM: 
   <form>
   <input type="email" class="form-control form-control-lg" placeholder="Email">
   <input type="password" class="form-control form-control-lg" placeholder="Password">
   </form> 
   Selector: form input
   Example: cy.get('form input').type("sundara");

Cypress Locator Strategy

1. Get Element

The get() method gets one or more elements from the DOM based on the CSS selector provided.

Syntax:cy.get(locator);
Example1:cy.get('#userid');
Example2:cy.get('input');
Example3:cy.get('input',{timeout:1000});     

2. Find Element

Find Elements under parent. If we use cy.get() it will search for the element on the entire document
However if we append find() and chain it then the scope of the searching will be limited to the parent element
Means it will find elements under the parent element.

DOM:

   <form>
   <input type="email" class="form-control form-control-lg" placeholder="Email">
   <input type="password" class="form-control form-control-lg" placeholder="Password">
   </form>

Syntax: cy.get('parentselector').find('childselector')

Selector:cy.get('form').find('input');

This command we can use in tables, list elements etc.

3. Select Element By Index

When cy.get() method returns a list of elements and we want to select a particular element based on index.
Then we can use the eq() method along with the get() method.

DOM:

   <form>
   <input type="email" class="form-control form-control-lg" placeholder="Email">
   <input type="password" class="form-control form-control-lg" placeholder="Password">
   </form>

Selector:cy.get('selector').eq('index')

Example:cy.get('input').eq(0).type("[email protected]");

Note: The index starts from zero(0)

4. Select Element based on text. (Contains)

Using contains() method we can fetch DOM element containing the specific text.

Example 1:

<button type="submit" class="btn btn-default">Submit</button>

This can be located using contains method.
cy.contains('Submit')


Example 2:

<form class="user_reg" action="/user/reg/do.php" accept-charset="UTF-8" method="post">
<input type="submit" name="submit" value="Log In"/>
</form>

We can also first locate the form using the class name & then use contains for the button text.
cy.get('.user_reg').contains('Log In')

5. Select visible Elements

Cypress supports jquery methods. Let's say you are trying to locate some elements and it has hidden elements too.
The best way is to filter out the invisible ones and select only the visible elements

Syntax: cy.get('locator:visible');

Example: cy.get(input:visible);

This will select only input elements those are visible on the page.

6. Use Chained methods to locate

Let's say we have lists and we want to follow the below strategy to locate element. Find the parent list element (ul)
-> find the list item (li)
-> Then select the second list item
-> check the text
-> Then click

Example:cy.get('ul.nav.navbar-nav').find('li').eq(1).contains('Sign in').click();

We can use this type of approach for selecting a navigation menu item, selecting from table, shopping cards etc.

7. Iterate over Elements

Lets say we have a menu list and we need to select menu item based on the text.
In this case we need to iterate over all elements under the menu list and compare with the desired text,
once found, we need to click on it. Cypress allows us to iterate over elements using .each() method

Demo Site: https://react-redux.realworld.io/#/?_k=30112w

cy.get('ul.nav.navbar-nav').find('li').each(($el, index, $list) => {

            const menuText = $el.text();
            console.log(menuText);
            if(menuText.includes('Sign in'))
            {
                console.log('condition satisfy');
                cy.wrap($el).click();
            }  
   });

Here the $el refers to the current element
index is the counter & $list is the element list
we can use any cypress command wrapping the $el with cy.wrap
If we want to use jquery methods then we can directly apply on $el.

8. Fetch Text From Element

Cypress doesn't have any method to fetch the text. So we need to use Jquery methods.

 
  cy.get('h1.logo-font').then((ele)=>{
        const text = ele.text();
        cy.log(text);
  })

we can use 'invoke' text method also

cy.get('h1.logo-font').invoke('text').then( (text => {
      expect(text.trim()).to.eq('conduit')                    
}));

9. Selects elements with attribute starts with text

DOM: <button class="btn btn-lg btn-primary pull-xs-right" type="submit">Sign in</button>
Command: cy.get('button[class^="btn"]').should('be.visible').click();

10. selects all elements with class btn & then filters out having the text Sign in

cy.get('.btn').contains('Sign in').click();


Note: Add cypress children(), parent(), parentsUntil(), sibling(), prev(), next()

Reference: https://docs.cypress.io/faq/questions/using-cypress-faq.html#How-do-I-get-an-element%E2%80%99s-text-contents

⚠️ **GitHub.com Fallback** ⚠️