cypress check element has an attribute

Cypress Check Element Has an Attribute

As a web developer, you may come across a situation where you need to check if an element has a certain attribute or not. Fortunately, Cypress makes this task easy with its built-in methods.

Method 1: Using the .should() Method

The first method to check if an element has an attribute is by using the .should() method in Cypress. This method allows you to assert certain conditions on a DOM element.

Let's say we have an element with the id "myElement" and we want to check if it has the "disabled" attribute:

cy.get('#myElement')
  .should('have.attr', 'disabled')

In the above code, we are selecting the element with the id "myElement" using the .get() method in Cypress. Then, we are using the .should() method and the 'have.attr' assertion to check if the element has the "disabled" attribute.

Method 2: Using the .invoke() Method

The second method to check if an element has an attribute is by using the .invoke() method in Cypress. This method allows you to invoke a function on a DOM element and get the result.

Let's say we have an element with the id "myElement" and we want to check if it has the "disabled" attribute:

cy.get('#myElement')
  .invoke('attr', 'disabled')
  .then((disabled) => {
    // Assert disabled is truthy
    expect(disabled).to.be.ok
  })

In the above code, we are selecting the element with the id "myElement" using the .get() method in Cypress. Then, we are using the .invoke() method to invoke the "attr" function on the element and get the value of the "disabled" attribute. Finally, we are using a callback function with the .then() method to assert that the "disabled" value is truthy.

Conclusion

These are two methods to check if an element has an attribute in Cypress. You can use either one depending on your preference and the situation at hand.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe