Utilizing a CSS selector to target a button nested multiple levels deep

Currently, I am conducting E2E tests on an application that lacks clear identification for the tags. I need to click on buttons nested deeply within the structure, some of which have the same name and properties as others.

The HTML code presents itself similarly to the following:

<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>

Due to having two buttons with the same name, I cannot simply use browser.click('button*=Button'). Instead, I am currently using this approach:

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

For the second button, a different selector is needed like this:

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

Although this method works, I have encountered several issues: - The code is not visually appealing and can be confusing for someone new to it - It is prone to breaking with even minor changes in the app's structure, unrelated to the buttons themselves

My query is whether there is a more efficient way to target these buttons under the given conditions.

Answer №1

If your HTML structure stays the same, you can utilize the fact that the second button is inside a div that is a sibling of another div. For instance:

/* 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>

Answer №2

One way to tackle this is by employing an XPath query

//div[.='Additional information']/following::button

The following button comes after a DIV labeled as "Additional information". Utilize this label to differentiate between the two buttons.

Answer №3

According to Selenium documentation, if a browser doesn't support a query, it will utilize Sizzle as a fallback option. This means you can use :contains() to select elements based on the text they contain, for example:

button:contains("Button")`

Furthermore, WebdriverIO has a slightly different syntax for achieving this functionality. Check out their documentation for more information:

browser.getTagName('button=Button'); // captures: "<button>Button</button>"


For additional details, refer to the WebdriverIO documentation

Explore more about selectors in the Selenium documentation

For specific information on using :contains() with Sizzle, check out the Sizzle documentation

Answer №4

Xpath is definitely the way to go!

Have you thought about incorporating indexing?

Here's the Xpath for the first button:

//button[1]

And here's the Xpath for the last button:

//button[last()]

Answer №5

There are multiple ways to access the element:

Here are a few examples:

// To click on the first button 
$$('button')[0].click();

// To click on the second button 
$$('button')[1].click();

Note: The above method is suitable if there are only two buttons on the page. For more buttons, consider other options.

Alternatively, you can chain selectors as demonstrated in this link

let buttonContainer = $('.fluid');
buttonContainer.$$('button')[0].click();
buttonContainer.$$('button')[1].click();

If you prefer accessing elements based on the .content div, you can use the following:

$('.fluid div.content:nth-child(1) >button').click();
$('.fluid div.content:nth-child(2) >button').click();

The choice of how to access the DOM elements is yours depending on your convenience.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting Issue with jQuery replaceWith in Loop

Trying to make it so that when the update button is clicked, the text on the left side becomes an input box: Click the update button and the text on the left will be an input box However, instead of just one input box appearing, all the text on the left s ...

Error Encountered: Codeception WebCurlException

Currently, I am using Codeception in conjunction with Selenium Webdriver and encountering a WebCurlException Error once I execute codecept.phar. Here are the steps I've taken: 1. I initiated the selenium stand alone server jar file via the command p ...

Encountering a java.net.unknown host exception while attempting to run Selenium scripts remotely in a grid from Jenkins operating in a Linux environment

Seeking assistance for the following issue: We have Jenkins running on a Linux server, attempting to execute Selenium scripts in a Selenium grid hosted on a Windows machine. The stage in our Jenkinsfile is as follows: Stage("Functionaltest") Checkout:scm ...

What is the best way to position an image in the middle of a Bootstrap 5 Carousel?

I utilized the Bootstrap documentation and everything is functioning properly, but I am facing an issue with aligning the logo in the center of the carousel, especially when the image transitions. I attempted using a relative parent element, but it seems ...

Challenges with Setting up reCaptcha

Issue arises while trying to implement reCaptcha. In the body of my basic HTML page, I have a form with the following content. <form action="/cgi-bin/new_forms/form.pl" method="post" name="pledgeform" onSubmit="return validate(this)"> All form info ...

Is it feasible to utilize HTML files to fetch information from a MYSQL database by utilizing PHP on the server?

I am trying to set up a form in an HTML file called index.html that includes some AJAX code linking to PHP for MySQL database connectivity. The idea is for clients to be able to insert, delete, and edit data in the database by filling out the form on index ...

The navigation bar vanishes when a picture is inserted below it

I encountered an unusual issue on my webpage. Everything was going smoothly with my navigation bar, even for mobile phones. However, as soon as I added a photo below the navigation bar, it disappeared... I'd like to keep the navigation bar visible, ...

What is the process for inserting HTML and CSS through the editor on DNN? Can markup be incorporated without the need for modules?

At my workplace, I do not have direct Host or Superuser access to DNN, and unfortunately, it is against company policy to grant me access to those accounts. This poses a challenge when trying to get my HTML/CSS to function correctly within the DNN HTML edi ...

Which software is recommended for converting Sass to CSS on a Linux operating system?

Just starting out with Sass and I've run into a snag. Currently following a tutorial that utilizes Scout as the Sass compiler for generating CSS. The issue is that Scout is compatible only with Windows and Mac, while I work on Ubuntu Linux. Any reco ...

What are the steps to create a basic chrome extension that functions as a countdown clock?

I am a beginner in the world of coding and I am currently working on creating a chrome extension that serves as a timer. My goal is to include the timer within the HTML popup file, allowing users to customize the settings themselves. Do you have any advice ...

using jquery to trap anchor in unordered list items

This section is dedicated to the menu on the website. The code for this menu can be found in the _Layout.cshtml() page. When the 'Neu Gesellschaft' page loads, I want to change the CSS of the anchor tag a. I attempted the following jQuery code: ...

Identifying all unused CSS class selectors in the code that do not have any CSS rulesets assigned

Is there a way to retrieve a list of all the CSS classes I have used in my code that do not have a corresponding "CSS ruleset" defined for them? For example: /*Definition (or Rule set) for .some-random-class doesn't exist or is ...

What are some strategies to enhance the responsiveness of this JQuery code?

I'm facing an issue while trying to create a progress bar that dynamically adjusts based on the device's width. In this particular scenario, whenever the device width changes, the progress bar's width remains static, causing it to break whe ...

List on the Left Side with Scroll Capability

In my ASP.NET web application that targets .NET 3.5 and utilizes an AJAX asp:UpdatePanel, I have structured the page layout using multiple div elements to divide the vertical space into sections - header, first content, second content, third content, and f ...

Adjust the width of xAxis[0] and xAxis[1] in Highcharts to their default values

Hi there, I need some help with Highcharts. Is it possible to adjust the width of xAxis[0] and xAxis[1] as well as reset the offset of xAxis[1] at runtime? I have a chart with two x-axes that need to be resized to fit different sized divs. You can see an ...

How can I center one middle position for my inputs and have the span align to the left?

How can I center my input fields with all the spans aligned to the left? I would like the inputs to be centered on the page, with supporting spans aligned to the left or right of the input lane. I am utilizing some Bootstrap 4 classes for this layout. C ...

Tips for implementing lazy loading with an owl carousel featuring background images

Is there a way to add lazy loading to a semi custom owl carousel that uses background images instead of regular img tags? I've tried using Owl carousel's function for lazy loading but it doesn't seem to work. How can I achieve this? This is ...

Is it possible to incorporate a LINK within the CSS GRID layout?

Hey everyone, I've encountered an issue with my link placement in the grid. I'm looking to turn the entire box into a clickable link. * { padding: 0; margin: 0; } body { font-family: Hiragino Kaku Gothic Pro W3, Arial; } .title-conta ...

To identify the dynamically inserted and generated div element amidst the other elements on the page

My goal is to have a new div generated and inserted over the other elements on the page when a button is clicked. Here is the markup I've written: <div id="parent"> <div id="d1"> </div> <div id="d2"> </div&g ...

Struggling to display the array after adding a new item with the push method

Seeking assistance in JavaScript as a newcomer. I have written some code to print an array once a new item is added, but unfortunately, it's not displaying the array. I am puzzled as there are no errors showing up in the console either. In my code, I ...