Search code examples
htmltestingcypresshref

Iterate through an html structure and find a specific href in an a


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

Example code:

<div class="navigation_outer">
   <div class="navigation">
      <div class="navitem ">
         <div class="glyph">
            <i class="fa fa-hashtag"></i>
         </div>
         <div class="label">Homepage</div>
            <a href="/homepage/" title="Homepage"></a>
         </div>
      <div class="navitem ">
         <div class="glyph">
            <i class="fa fa-hashtag"></i>
         </div>
         <div class="label">Live Events</div>
            <a href="/homepage/events" title="Live Events"></a>
         </div>
      <div class="navitem ">
         <div class="glyph">
            <i class="fa fa-hashtag"></i>
         </div>
         <div class="label">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!

EDIT!

cy.contains('div', 'Live Events').next().click() worked for me so thank you very much for the replies


Solution

  • 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()