Element Attributes

📺 Watch this recipe in video Get And Set Multiple Elements Attributesopen in new window.

<ul>
  <li data-product-id="a11">Apples</li>
  <li data-product-id="b20">Oranges</li>
  <li data-product-id="c11">Bananas</li>
</ul>

Let's find all li elements and check their data-product-id attributes. Using jQuery attr methodopen in new window returns only the first element's value.

cy.get('li')
  .should('have.length', 3)
  .invoke('attr', 'data-product-id')
  .should('equal', 'a11')

To get the attribute from every element, write custom code, or use cypress-mapopen in new window. From every plain DOM element inside the jQuery we get the attribute by calling the element's getAttribute method.

cy.get('li')
  .should('have.length', 3)
  .mapInvoke('getAttribute', 'data-product-id')
  .should('deep.equal', ['a11', 'b20', 'c11'])

If you want to set the same attribute to the same value for all elements, you can use jQuery attr methodopen in new window.

// set the attribute "data-product-id"
// for all LI elements to the same value "x1"
cy.get('li')
  .should('have.length', 3)
  .invoke('attr', 'data-product-id', 'x1')

Let's confirm our attributes change

cy.get('li')
  .should('have.length', 3)
  .mapInvoke('getAttribute', 'data-product-id')
  .should('deep.equal', ['x1', 'x1', 'x1'])

If you want to set a different attribute value, pass a callback function to jQuery attr methodopen in new window.

// set the attribute "data-product-id"
// for all LI elements to dynamic values
cy.get('li')
  .should('have.length', 3)
  .invoke(
    'attr',
    'data-product-id',
    (k, currentAttributeValue) => {
      return `${k + 1}-${currentAttributeValue}`
    },
  )
// confirm the new attribute values
cy.get('li')
  .should('have.length', 3)
  .mapInvoke('getAttribute', 'data-product-id')
  .should('deep.equal', ['1-x1', '2-x1', '3-x1'])