Home > Blockchain >  Iterate through an html structure and find a specific href in an a
Iterate through an html structure and find a specific href in an a

Time:05-24

does anyone how how to iterate though a structure and look for a specific href using cypress??

Example code:

<div >
   <div >
      <div >
         <div >
            <i ></i>
         </div>
         <div >Homepage</div>
            <a href="/homepage/" title="Homepage"></a>
         </div>
      <div >
         <div >
            <i ></i>
         </div>
         <div >Live Events</div>
            <a href="/homepage/events" title="Live Events"></a>
         </div>
      <div >
         <div >
            <i ></i>
         </div>
         <div >Filler</div>
         <a href="/homepage/filler" title="Filler"></a>
      </div>
   </div>
</div>

Say I wanted to find href="/homepage/events" by iterating though that html structure, and click on it for it to take me to that link.

Is there a way of doing this? Because I've been trying to use find(), each(), should(), contain(), invoke(), but nothing seems to work for me

Any help is appreciated, thanks!

CodePudding user response:

You can use each to iterate through the elements and then click on href="/homepage/events"

cy.get('a').each(($ele) => {
  if ($ele.attr('href') == '/homepage/events') {
    cy.wrap($ele).click()
  }
})

CodePudding user response:

To go directly to it, specify the href as part of the selector

cy.get('.navitem a[href="/homepage/events"]').click()

In the above selector, a[href="/homepage/events"] is used to specify the <a> element that has href="/homepage/events" as an attribute. It gets the single element you need because href="/homepage/events" is unique.

You could also use the title="Live Events" attribute because it is also unique to your target element.

cy.get('.navitem a[title="Live Events"]').click()

One more option is to search by label

cy.contains('div', 'Live Events')
  .next()                          // next element is <a>
  .click()
  • Related