...

/

Selecting Elements With Cypress

Selecting Elements With Cypress

Learn how to select elements with Cypress.

Using different HTML Elements

Let’s dive into Cypress by learning how to select elements in a webpage. In this lesson, we will learn the advantages and disadvantages of different element selection methods and employ the following demo application. Let’s launch the application by clicking the “Run” button and see how it looks in the browser.

describe("Landing page", () => {
  it("select Hello World", () => {
    cy.visit("/");

    cy.contains("Hello World");

    cy.get("h1");
  });
});

export {};
A Next.js demo application

The home page at the / path includes multiple elements, e.g., H1 and H2 headings, a list of fruits, an HTML form, an input field, and a button.

Selecting elements with the get() method

The cy.get() command allows selecting elements using jQuery selectors, which are a mixture of CSS selectors and some custom ones, such as the following:

  • Element tag

  • Class

  • ID

  • Attribute

  • Location

  • Combination of the aforementioned items

Let’s run the code below to get all h1 elements.

describe("Landing page", () => {
  it("select h1", () => {
    cy.visit("/");

    cy.get("h1");
  });
});

export {};
Cypress h1 test
...