Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get native HTML element in Cypress

How do I get an underlying native HTMLElement (or Element or Node...) from a Cypress query?

const el = cy.get('.foo').children().first()
//    ^ this is of type Cypress.Chainable<JQuery<HTMLElement>>

I would like to access the native HTMLElement instance in el.
I have tried el[0] but the result is of type any.

like image 415
ᅙᄉᅙ Avatar asked Nov 15 '19 15:11

ᅙᄉᅙ


People also ask

How do I get an element's text contents in Cypress?

How do I get an element's text contents? Cypress commands yield jQuery objects, so you can call methods on them. If the text contains a non-breaking space entity &nbsp; then use the Unicode character \u00a0 instead of &nbsp; . Tip: watch the Confirming the text with non breaking space entity video.

How do you get attribute values in Cypress?

To find elements by data attribute, query using the attribute selector. cy. get() yields a jQuery object, you can get its attribute by invoking the . attr() method.

How do I get text from a locator in Cypress?

Cypress can validate the text on an element with the help of jQuery text() method. This method shall help us to fetch the text content on the selected element. We can also put assertions on the text content of the element. cy.

How do I find an element in HTML?

Finding HTML Elements by CSS Selectors If you want to find all HTML elements that match a specified CSS selector (id, class names, types, attributes, values of attributes, etc), use the querySelectorAll() method. This example returns a list of all <p> elements with class="intro" .


1 Answers

In cypress, first() is a command that will be chained to .get() and retry for that whole selection until timeout. That is why you can't really obtain the native element from it.

You can however yield the command, and access the element inside .then() by passing a function to it.

For example, from the Cypress documentation on this EXACT question:

cy.get('.foo').then(($el) => {
  const el = $el.get(0) //native DOM element
})
like image 102
istepaniuk Avatar answered Sep 25 '22 02:09

istepaniuk