Obtaining a list of child span elements using xpath in Selenium

I am looking to retrieve all child span elements based on the following xpath

//label[@for='someText']/span

Expected result:

<span class="someClass">"Find this text"</span>
<span id="someId">"Find this text2"</span>

The number of nested span elements can vary dynamically, in this case there are 2 span child elements, but it could be different.

Purpose: The goal is to extract text from each element for comparison purposes. Once I have these elements, I can loop through them and retrieve desired data based on their attributes.

Example HTML structure:

<label for="someText">
  <span class="nestedClass">
    <h2 id="id">
      <span>"Hello"</span>
    </h2>
    <span class="someClass">"Find this text"</span>
    <br>
    <span id="someId">"Find this text2"</span>
  </span>
</label>

Is there a way to achieve this? Any suggestions or alternative methods would be greatly appreciated.

Thank you.

Answer №1

Utilizing either of the xpath methods should be effective for your situation.

List<WebElement> elements = driver.findElements(By.xpath("//label[@for='someText']/span/span"));

Alternatively, you can exclude span tags that are descendants of an h2 element.

List<WebElement> elements = driver.findElements(By.xpath("//label[@for='someText']/span//span[not(ancestor::h2)]"));

Answer №2

Consider utilizing this XPath:

//label[@for="specificText"]/span/*[not(*)]/text()

The conditional *[not(*)] is used to target only the terminal span elements.

Answer №3

To cycle through elements, you have the option of using the size() method or navigating the list with a for loop.

List<WebElement> mySpans = driver.findElements(By.xpath("//label[@for='someText']/span//span"));
        
        int totalSpans = mySpans.size(); // Get the total number of spans dynamically
        
// Alternatively, you can iterate through the webelements in the list using a for loop
        for(WebElement span : mySpans)
        {
            System.out.print(span.getText());
        }

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

Is there a dependable resource for mastering Protractor along with the Jasmine Framework in Eclipse using JavaScript?

Starting a new role at my organization where I will be testing Angular JS applications. Can anyone recommend a good website for learning PROTRACTOR with JAVASCRIPT using the JASMINE Framework? (Would prefer if it includes guidance on Eclipse IDE) Thank yo ...

Retrieving selected options from a jQuery mobile multiselect for database storage

I'm currently working on extracting values from a select list in a jQuery mobile application. Here's the markup for my select element: <div data-role="fieldcontain"> <label for="stuff" class="select">Stuff:</label ...

Alignment of Material-UI dialogue buttons on the left side

I have a Dialog containing three buttons as shown below: https://i.stack.imgur.com/T6o35.png Here is the JSX code: <DialogActions classes={{ root: this.props.classes.dialogActionsRoot }} > <Button classes={{ root: this.props ...

Looking for assistance with resizing and repositioning an image within a viewport?

The JSFiddle code can be found at this link - https://jsfiddle.net/pmi2018/smewua0k/211/ Javascript $('#rotate').click(function(e) { updateImage(90, 0) console.log("rotation"); }); $('#zoom-in').click(function() { updateImage(0 ...

Am I on the right track in my understanding of how document and viewport relate to mouse position in JavaScript?

After reviewing responses from a previous inquiry, it is evident that both pertain to the x and y coordinates of mouse positions. In relation to the document and In relation to the viewport. I have delved into an article on QuirksMode, yet I feel ther ...

Mastering Yii2: Implementing Javascript Functions such as onchange() in a View

One of the elements in my project is a checkbox: <div class="checkbox"> <label> <?= Html::checkbox('chocolate', false) ?> Chocolate </label> </div> In addition to that, I also have a span ta ...

Why does it appear that Angular is undefined in this straightforward Angular demonstration?

I'm completely new to AngularJS and I've encountered an issue. Yesterday, I ran a very simple AngularJS application that I downloaded from a tutorial and it worked perfectly. The application consists of 2 files: 1) index.htm: <!DOCTYPE htm ...

Ways to remove all HTML elements from a string

Check out the code that I currently have: I am looking for a way to prevent users from entering any HTML tags in the "Add Responsibilities" field. For example, if a user enters the following: <div>Test</div> It should only display the text l ...

What is the best way to establish a maximum limit for a counter within an onclick event?

I'm struggling to figure out how to set a maximum limit for a counter in my onclick event. Can someone help me? What is the best way to add a max limit to the counter of an onclick event? Do I need to use an if statement? If yes, how should it be w ...

Steps to initiate my selenium-standalone server: Execute the command "selenium-standalone start"

I'm currently facing a challenge while trying to execute a test script in WebDriverIO. After cloning the code from wdio-cucumber-framework, I am unable to get selenium-standalone to start properly. The error message indicates an issue with geckodriv ...

Dynamically modifying the styling of elements within an iframe

In my current project, I encountered a challenge with changing the background color to black and the body text color to white within an iframe. Additionally, all elements that are originally styled with black in an external stylesheet also need to be chang ...

Running Protractor tests can be frustratingly sluggish and frequently result in timeouts

After spending most of the afternoon struggling with this test, I've tried different approaches but none seem to work. The task at hand is searching for users within the company, generating a table, and selecting the user that matches the name. Curren ...

Is it possible to incorporate a next.js image onto the background design?

I've encountered an issue while attempting to create a fixed background image with a parallax effect using Tailwind CSS and Next.js Image. If you need to see an example of this in action, check out this Template Monster theme. Here's the code s ...

Can we dynamically add an identical DOM structure by clicking a button using jQuery?

I currently have ten text fields within a single div. I am interested in including another set of ten text fields with the same name, class, and id. Is there a way to recycle the existing DOM structure mentioned above, or will I need to generate and add t ...

Is there a way I can obtain the code for a message box?

When I refer to a message box, I am talking about a container that gives users the ability to input their text and access different features like BOLD, ITALIC, color, justify, etc., in order to customize their message's appearance! (Think of it as the ...

The issue with displaying inline block is that the divs are not appearing side by side on the

Two of my div elements, namely form-panel and data-panel, are currently not aligned on the same line. How can I use display:inline-block to align them in a single line? Please review the code provided below. I have already used display:inline-block on both ...

Is there a way to restrict my input to only 10 numbers without allowing any characters?

Is there a way to restrict the phone number input to only allow 10 numbers and exclude any other characters? Currently, setting the maxLength attribute limits the characters to 10 but allows additional characters as well. If I change the type attribute to ...

I am seeking to showcase an image in a window, and upon the image being clicked, execute the code in a separate window

I am looking to showcase the image provided below. <img src="http://gfx.myview.com/MyView/skins/livesample/image/livesample.gif" alt="" border="0"><a/> Once the image is clicked, I want it to execute the following code. How can I ensure that ...

Update JSON data in ng-blur event using AngularJS

Could you offer some guidance on how to push the content from a text box into JSON when I click outside of the box? Below is the code for my text box: <input type="text" name="treatmentCost" class="form-control" ng-model="addTemplate" /> And here i ...

spark of unique substance

Having trouble with cycle2 as all images are briefly displayed when the page loads. I tried the recommended solution http://jquery.malsup.com/cycle/faq.html but it didn't stop the flashing, indicating a different issue: The suggested fix for Cycle is ...