Tips for choosing nested elements with basic CSS selectors like nth-of-type or nth-child for Selenium

Is there a way to select the paragraph tag for B (or C) by utilizing nth-child or nth-of-type in Selenium WebDriver?

<tr>
    <td>
        <p class="myClass">A</p>
    </td>
</tr>
<tr>
    <td>
        <p class="myClass">B</p>
    </td>
</tr>
<tr>
    <td>
        <p class="myClass">C</p>
    </td>
</tr>

Context: I am exploring automation testing with Selenium WebDriver, and faced issues with selecting elements using standard CSS selectors like nth(i).

While I can successfully select the first element, I encounter difficulties with selecting the nth element. This could be due to nesting.
These attempts have failed:
.myClass:nth-of-type(2) (locator not found, per Selenium IDE)
.myClass:nth-child(2) (locator not found, per Selenium IDE)

Answer №1

For those using Selenium WebDriver, the following code snippet can be helpful:

String cssSelector = ".myClass";
List<WebElement> elementList = driver.findElements(By.cssSelector(cssSelector));
WebElement targetElement = elementList.get(index);

While not perfect, this solution gets the job done.

Answer №2

Could the css selector function for selecting based on content work for you?

driver.FindElements(By.cssSelector("p.myClass:contains('B')"));

Response: No, as :contains() is a JQuery pseudo-function.

If you are using C#, you can import SizSelCsZzz for JQuery functionality. Then you would be able to do:

driver.FindElements(new ByJQuery.ByJQuerySelector("p.myClass:contains('B')", true));

In addition, when it comes to nth-child, this is also a JQuery pseudo-function. In similar fashion:

using SizSelCsZzz;

namespace YourNamespaceHere
{
   public class YourClass
   {
      By selectB = new ByJQuery.ByJQuerySelector("p.myClass:nth-child(2)", true);
   }
}

Answer №3

To choose option B, employ the following code:

table tr:nth-child(2) td p {/*insert your custom styles here */}

Answer №4

Although I am not familiar with selenium, you can try using standard CSS selectors to target 'C' in the following way:

table tr + tr + tr > td > p {color:blue;}

Answer №5

Sibling elements are not present with the p tag as they are in separate columns. To target specific rows, consider using the nth-child pseudo-class on the tr tag. An example would be changing the background of odd rows:

table tr:nth(odd){
    background-color: #color-code;
}

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

Find the button for uploading files using Selenium

I am encountering an issue with trying to click the button displayed below (image and HTML). Despite attempting to locate it using both xpath and ID, Selenium is still unable to find it. https://i.stack.imgur.com/KMMku.png <input id="wsUpload1" type= ...

The capybara::dsl::module does not have a defined delegate method

I am encountering an issue with my capybara monkey patch while working with jquery-ui. It works smoothly on Ubuntu, but when I switch to Windows, I face the following error message despite having all the necessary dependency gems installed: Undefined meth ...

Dynamic HTML gallery that supports the addition of fresh images

Looking to showcase images from a local folder in a slideshow on a simple web page? The page should automatically update when new images are added or removed from the folder. I am not an expert and prefer a minimalist design with perhaps just a transitio ...

Add custom CSS styles to a webpage using the CSS Style element retrieved from

I am working on an HTML page that has a TextArea and label. My goal is to create CSS classes in the TextArea and apply them to the label: <textarea id="txtCSS" name="txtCSS" rows="4" cols="50"> .FC{color:gr ...

Issue with creating a new jstree node

I recently put together a basic jstree. When I click on a link, it triggers the createNode() function. This function utilizes the create feature from the API to generate a new node. It appears to be a common issue with jQuery that I am encountering. Any ...

How to customize the color of radio buttons in JFXRadioButton using CSS

I am facing an issue with customizing the styling of JFXRadioButton component from this library : jfoenix.com I want to modify the color of the circle, but the default class is not working. Are there any suggestions or solutions available? (The colors me ...

The hover effect is being applied exclusively to the final React component

When using next.js and tailwindCSS for styling, I created a custom component that includes tags. The issue arises when multiple instances of this component are placed on the page, as only the last one is getting the desired hover effect. "index.js" import ...

Tips on storing browser sessions in Selenium

I am currently utilizing Selenium for logging into an account. My goal is to save the session after logging in so that I can access it again the next time I run my Python script without having to log in again. Essentially, I want the Chrome driver to fun ...

Jenkins consistently delivers positive outcomes with TestNG and Selenium testing frameworks

Recently I started using Jenkins and I am facing an issue with my builds. I am currently working on writing UI tests using Selenium, Java, and TestNG. My main concern is that despite having failing tests, Jenkins always displays 'Finished: SUCCESS&apo ...

How can I position a div element inside another fixed div element?

I'm working on a layout with a fixed gradient div that contains all my content. However, I want the content to be scrollable instead of fixed. How can I make this happen? Here is the current structure: <body> <div class="wrappe ...

What is the best way to choose all initial elements within a single row using CSS?

Is it possible to target all the first elements in a single row? I know this is an unusual request, but I have a row that contains block elements. I want to apply CSS styling to each of the first elements. Here is the row: <ul class="slides"> &l ...

Steps to obtain context and transition to webview context:

Currently, I am in the process of testing a Windows hybrid application. In order to obtain contexts, I have utilized the following codes. However, upon launching, I encountered an UnsupportedCommandException. Below is the code snippet I am working with: p ...

CSS - Utilizing Flexbox for creating inline lists that adjust based on text length

I have a set of radio buttons arranged like this: I want to utilize flexbox to display them horizontally when there is sufficient space, similar to this: However, the current setup uses a min-width media query for layout breaking, which can lead to text ...

Steps to ensure a dropdown menu remains expanded when its nested menu is selected

Check out this dropdown list here, but the issue arises when clicking on a nested menu item such as "Books Registration". Once that page loads, the dropdown menu collapses like shown here. Here's a snippet of the dropdown code: <ul class="nav nav- ...

Can you explain the slow parameter feature in Mocha?

While configuring mochaOpts in Protractor, one of the parameters we define is 'slow'. I'm unsure of the purpose of this parameter. I attempted adjusting its value but did not observe any impact on the test execution time. mochaOpts: { re ...

Experiencing unexpected behavior with my code. Utilizing ArrayList and a for loop in my Selenium Webdriver Java script

Recently, I've delved into working with Selenium Webdriver using Java. Check out the code snippet below: List<LineDashboardDetails> LineDashboardDetailList = new ArrayList<LineDashboardDetails>(); LineDashboardDetails objLineDetai ...

The various options in the dropdown menu are descending in order

I am currently facing an issue with a dropdown menu that contains the list of products offered by our company. Specifically, one of the product names, Hotel Management Solutions, is appearing on multiple lines instead of a single line in the dropdown menu. ...

Has any of my predecessors been hidden from view?

How can we detect if one of an element's ancestors has the display:none property set without having to traverse up the DOM Tree? ...

What steps should be followed to effectively incorporate Google Fonts into a Material UI custom theme for typography in a React/TypeScript project

Hey there, I'm currently working on incorporating Google fonts into a custom Material UI theme as the global font. However, I'm facing an issue where the font-weight setting is not being applied. It seems to only display the normal weight of 400. ...

CSS problem: HTML element moving to the right upon clicking

Currently, I am utilizing a jQuery popup to present additional information to users. The setup involves having a link on the page that triggers the popup to appear from the top. The popup script being used is sourced from CodePen. However, an issue arises ...