简体   繁体   中英

How can I locate an element which was created with Javascript and is not present in the document.body?

I have an application which plays audios and I am writing some tests for it using Cypress.

The thing is that the audio tags for the audios are created using Javascript, new Audio() , and I am having trouble querying these audio tags.

When I add an element, such as an audio tag, using standard HTML, I can find it in the document.body .

Now, how can I locate an element, which was created using Javascript, such as new Audio() ?

If the elements you seek are truly outside of <body> (which is possible but not common), then this code can find them

cy.document()
  .find('body')
  .next()        // sibling element to <body> 
  .should('have.text', 'created in javascript script')   // verifies in my example

Or use <html> as the base element ( <body> is the default base element)

cy.document()
  .find('html')
  .contains('div', 'created in javascript script')

This is the DOM I tested on - the bottom <div> is added after <body> when the page loads.

<html>

<head></head>

<body>
  <div>Normal Html element</div>
</body>

<div>created in javascript script</div>

</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM