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

Adjusting the color of text based on the fulfillment of a condition

Is there a way to change the text color of a variable based on its value in PHP? For example, if the $status is set to admin, can we display it in red when echoed out using <h3>Status: <?php echo $status; ?></h3>? I'm not quite sure ...

What could be causing all of my Bootstrap accordion panels to close at once instead of just the one I selected?

When implementing Bootstrap accordions in my projects, I encountered an issue where closing one accordion would cause the others to also close when reopened. To address this problem, I utilized the collapse and show classes in Bootstrap to enable users to ...

What is the best way to flip cards with the onClick event in JavaScript?

My cards are currently facing down with the code* provided. What steps should I take to flip them face up using onClick functions? Furthermore, how can I store the IDs in an Array and use them to retrieve images from my image collection? HTML <table s ...

Choosing values randomly from dropdown using selectByIndex method within the Selenium Hybrid Framework

I am currently utilizing a Hybrid Framework, incorporating Object, Data, and Keyword components. I've encountered an issue with selecting a random value from a dropdown based on its index. Within my input file where I have specified the test data Tes ...

Apply a class to each consecutive element following the current one until reaching a child element with a

My goal is to apply a "bg-info" class using jQuery to all rows (tr) that come after odd rows with a child element of "test". The "bg-info" class should be removed when a row with a child element of "test" is encountered, and then re-applied when the next o ...

When utilizing an API to render text into a div, the offsetHeight function may return 0

I'm working with a div that displays text fetched from an API call. I'm trying to implement a See more button if the text exceeds 3 lines. Here is my approach: seeMore(){ this.setState({ seeMore: !this.state.seeMo ...

Achieving space between elements using Flexbox with a line separating each row

I have already found a solution to this question, but I am interested in exploring better alternatives. My goal is to utilize flexbox to create rows of items with equal spacing and dividing lines between them. The examples provided in the code snippet achi ...

The functionality of activating a button is not functioning as expected in AngularJS framework

Next to the question I have linked here, I am exploring a different approach. As a beginner in AngularJS/Cordova/Ionic, my goal is to achieve different outcomes when the "Eingepasst" button is clicked, each with unique logic compared to "Gewonnen" or "Ver ...

Harness the power of Selenium within Odoo version 13 to enhance

Is it possible to utilize selenium or a similar tool in an odoo module? While running selenium alone, everything works fine. However, when I integrate it into an odoo module, I encounter an error. selenium.common.exceptions.SessionNotCreatedException: Me ...

Concealing specific sections of HTML content in a webview on the fly

I've been experimenting with a proof of concept feature to implement the ability to conceal certain parts of a web page loaded in a webview, but I seem to be encountering some issues... Within a UIWebview extension, I have something similar to this c ...

Encountering issue: Unable to establish a connection with FirefoxBinary binary on port 7055

I'm encountering an issue when trying to run a Selenium test using a Maven project. The error I am receiving is: "Failed to connect to binary FirefoxBinary(C:\Program Files (x86)\Mozilla Firefox\firefox.exe) on port 7055." When the test ...

Steps for generating instances of an HTML page and dynamically adding them to a list on the main page

I have a main HTML page and I need to insert a dynamically generated list from a template in another HTML file that I created. The template for each item in the list is located on a separate HTML page. My goal is to create multiple instances of this HTML ...

Even though my test cases are running successfully on my local machine, they are not being marked as passed

When running my selenium test case on browserstack, the last 3 steps are being skipped and marked as UNMARKED. The suite report on Slack indicates that the test cases have passed, but upon closer inspection they show as unmarked.view image here Interestin ...

jwt io - unable to change the predefined value

Is there a way to clear the default value in the textbox on this link - , and replace it with my token? I've tried using .clear() and .sendkeys(keys.backspace()), but it's not working. Any suggestions on how to accomplish this task successfully? ...

Creating visually pleasing HTML emails with uniform table data heights

Struggling with Outlook while designing an HTML template. My row has 2 td elements with different content, and setting equal heights is proving to be a challenge. The fixed height on the td causes issues when switching to mobile view in Outlook as text wra ...

``Do not forget to close the modal window by clicking outside of it or

I am looking for a way to close the modal window either when a user clicks outside of it or presses the escape key on the keyboard. Despite searching through numerous posts on SO regarding this issue, I have been unable to find a solution that works with ...

Tips for managing the save file dialog box in Firefox with Selenium using C#

I am currently working with Selenium to test a website that includes the ability to download online videos. The website is built using ASP.NET. Whenever I click on the download button, a save file dialog pops up which Selenium is unable to handle. Is the ...

Tips for making a Bootstrap dropdown submenu appear as a 'dropup'

I'm using a Bootstrap dropdown menu with a submenu that should drop upwards while the rest of the menu drops down. How can I achieve this? Here is the code snippet: <div class="dropdown"> <a class="inputBarA dropdown-toggle" data-toggle= ...

Specify the WebDriver path in the build.gradle file for Selenium test scripts instead of programmatically configuring the System Property

When it comes to my Selenium test programs, I've been consistently setting the absolute path to webdriver executables by using System properties. For instance - System.setProperty("webdriver.edge.driver", new File("webdrivers/Mi ...

Display email address in a concise manner

Managing user information in my project involves capturing both username and email address. While the username is optional, the email address is mandatory with a maximum length of 100 characters. My issue arises when the email address exceeds 60 character ...