Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a css selector to grab a deeply nested button

I am currently doing some E2E tests on an app that doesn't have anything to easily identify the tags. I need to click a deeply nested buttons, which on occasion have the exact same name and properties as others.

The HTML code looks something like this:

<div class='.ui .row'>
  <div class='.ui .fluid'>
    <div class='.content'>
      <div>
        <div class='.field'>
          <button>Button</button>
        </div>
      </div>
    </div>
    <div class='.content'>
      <div>
        <div>Some other stuff</div>
        <div class='.field'>
           <button>Button</button>
        </div>
      </div>
    </div>
  </div>
</div>

Because we have two with the same name I couldn't just do browser.click('button*=Button'). The way I am currently getting around to it is by this:

browser.click('div > div > div > div > div > button')

while the second button, I would have to do something like this:

browser.click('div > div > div:nth-child(2) > div > div:nth-child(2) > button')

Despite it working, I have a few problems with this: - it doesn't look pretty and isn't easily readable for someone who may just be picking up this code - it will go stale with the most minute changes to the app, even if it has nothing to do with the buttons

My question is if there is a better to select these buttons given these circumstances.

like image 301
theJuls Avatar asked Jul 14 '26 18:07

theJuls


1 Answers

If your markup remains similar, you can take advantage of the second button being nested inside a div that is a sibling of another div. Example:

/* style the first button */
button {
  color: red;
}

/* style the second button */
div + div button {
  color: blue;
}
<div>
  <div>
    <div>
      <div>
        <div>
          <button>Button</button>
        </div>
      </div>
    </div>
    <div>
      <div>
        <div>Some other stuff</div>
        <div>
           <button>Button</button>
        </div>
      </div>
    </div>
  </div>
</div>
like image 94
sol Avatar answered Jul 17 '26 20:07

sol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!