Exploring Selenium with Java: Uncovering the Method to Locate and Identify a Specific Nested Element When Sharing Identical Parent Elements

If I have a page structured like this:

<div class = "A">
   <h1>AA</h1>
   <p>This</p>
</div>

<div class = "A">
   <h1>BB</h1>
   <p>This</p>
</div>

And each time the page is loaded, there are random "class A" divs in random order with headings like: "CC", "DD", etc... How can I locate and click on the link "This" within the "BB" div? This is what I've attempted so far:

driver.findElement(By.xpath("//*[text()='BB']")).findElement(By.xpath("//*
[text()='This']")).click();

I've also tried:

WebElement name = driver.findElement(By.xpath("//*[text()='BB']"));
name.findElement(By.xpath("//*[text()='This']")).click();

However, in both cases, I always end up clicking on the "This" in the "AA" div. If the order of the divs changes randomly next time the page loads, hardcoding it to always click on the second element won't be effective.

So, I am looking for a solution to target the "This" link within the "BB" div based on the condition that "BB" exists.

Answer №1

The concept is as follows:

  • Retrieve all elements with class name "A" and store them in a list.
  • Check for header text that includes "BB".
  • If found, select the paragraph tag of that specific class "A" index.
  • Click on "This".

See below for the full code implementation.

List<WebElement> allClass = driver.findElements(By.className("A"));
String targetHeader = "BB"; 

for(WebElement element : allClass){
    WebElement headerElement = element.findElement(By.tagName("h1"));
    if(headerElement.getText().equalsIgnoreCase(targetHeader)){
        WebElement thisParagraph = element.findElement(By.tagName("p"));
        thisParagraph.click();
        break;
    }
}

Answer №2

If you want to locate and select the link labeled This contained within a div with the class name BB, you can achieve this by implementing the subsequent block of code:

driver.findElement(By.xpath("//div[@class='A']/h1[text()='BB']//following::p[1]")).click();

Answer №3

Give this XPath a shot

//div[@class='X']//h2[text()='YY']//following::q

OR

//div[contains(@class,'X')]//h2[text()='YY']//following::q

Sample Code:

WebElement clickAction= driver.findElement(By.xpath("//div[contains(@class,'X')]//h2[text()='YY']//following::q"));
clickAction.findElement(By.xpath("q[text()=='That']")).click();

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

Formatting text and images in CSS

Looking to align images at the bottom of each column in a div with 3 columns, but struggling due to varying text lengths. Any tips on how to achieve this? https://i.sstatic.net/fuPgl.png Thank you, Carolin #content_row{ margin-top:150px; marg ...

The concept of reusing tests within TestNG

Looking to automate tests for a web application with complex process workflows? I have already set up a Page Object Model using Selenium WebDriver for interacting with the application components. Now, I am preparing to create automated tests for this spec ...

Loading CSS files in Next.js can sometimes require additional time for the styles to

Currently, I am working on a Next.js and Spring Boot project. However, I am facing issues with the loading of CSS files as they are taking a considerable amount of time to load. When I open a page, initially it appears without any styling, but after a few ...

Navigate to the first item on the menu in the Chrome browser

Why does the First Menu Item (.chosen) jump in Chrome Browser when refreshed? It seems like it's changing the Padding-Right and Padding-Bottom. Please review the code and help me solve this irritating issue. It works fine in Firefox. <body> ...

Unable to modify the font color to white on the CSS navigation bar

I've been attempting to alter the color of the text in my .blou class to white within my navigation menu in WordPress, but for some reason, the color isn't changing. This issue is occurring with the WordPress theme I am using. .nav-menu ul li a ...

Switch up the text inside a div using jQuery

I am developing a small grocery shopping application. My goal is to create a page where users can view the contents of their shopping cart by clicking a button. I have designed a template that displays the contents in a white space. The idea is to store ...

Understanding the scope of variables in HTML files, JavaScript files, and PHP files when echoing statements

Is there a way to define a global javascript variable that can be accessed from multiple places within an HTML page? I need the variable to be accessible in three specific locations: Within the code of the HTML page favorites.php. Inside a separate javas ...

Tips for preventing flex items from having equal height when collapsing

When I try to place elements from an array in a list with display flex, the height of other elements gets modified when one is collapsed. I have attempted different display and inline placement on li elements but nothing has worked so far. Is there a way ...

After running my CSS through the validator at http://www.css-validator.org/validator, I encountered a Parse Error. Any suggestions on how I can resolve this issue?

Here are the CSS codes for my media query section. @media (min-width:320px) and (max-width:575px){ .chakra{ width: 100%; float: unset; margin: auto; } } ...

When provided with no input, the function will output true

I'm having trouble understanding this problem! I've implemented a basic jQuery validation that checks if an input field is empty when a button is clicked. http://fiddle.jshell.net/fyxP8/3/ I'm confused as to why the input field still retu ...

How to Utilize USB Devices with Node-Webkit?

I am in the process of creating a node-webkit application that must be compatible with all three major desktop operating systems (Windows, Mac, and Linux). My goal is to establish a connection between my app and a USB device that is plugged in, but I am en ...

Using a Do/While loop in combination with the setTimeout function to create an infinite loop

Having trouble with this script. The opacity transition works fine, but there seems to be an issue with the loop causing it to run indefinitely. My goal is to change the z-index once the opacity reaches 0. HTML <div class="ribbon_services_body" id="ri ...

jQuery SlideOver - Arranging Divs in a horizontal layout

Currently, I am working on an application wizard that is designed to slide panels in order to display different sections of the resume application. You can view my site here: . The issue I am having is that when you click anywhere on the form, the panels a ...

Basic color scheme

I'm attempting to change the background color behind a partially transparent .png div. The CSS class that modifies the div is ".alert". Manually editing the .alert class background color works perfectly, and now I want to automate this on a 1-second c ...

jscrollpane does not work properly in Firefox, but it functions correctly in Chrome

I am currently utilizing jScrollpane to display a combination of images and a div in a horizontal format. While I have successfully implemented it on Chrome, it appears that Firefox is not applying the CSS correctly to prevent images from wrapping, resulti ...

I am experiencing an issue with using double quotation marks in VS Code

Whenever I press the double quote symbol like this "", the cursor automatically moves to the end. While this may be natural, I would prefer the cursor to move inside the double quotes automatically when pressing them. Additionally, it's a bi ...

Tips for integrating PHP with HTML5 while developing a Blackberry native application that utilizes Blackberry websockets

I'm currently working on a basic HTML5 page that includes inline PHP script. I'm looking for advice on how to transform this app so it can be used with Blackberry WebSockets. For example, I want to develop a native app using HTML5. ...

Top tips for implementing a two-way relationship in an object-oriented model

As I dive deeper into object-oriented modeling, I find myself grappling with the challenge of establishing a bidirectional relation. Consider a scenario where a Customer can have multiple Orders, creating a one-to-many association between the Customer and ...

Centered alignment with extra margin

How can I horizontally center an element on a page with a margin of 100px on both the left and right if the viewport gets smaller? Do I need to use a parent container for this layout? margin: 0 auto; margin-left: 100px; margin-right: 100px; ...

Creating a visualization tool for Pareto analysis with Javascript, Html, and JSON

Currently, I am on the lookout for plugins, examples, or any related resources that can assist in creating a Pareto Chart for an HTML page. My goal is to construct it using HTML, style it with CSS, and populate data through JSON. While I am open to buildin ...