Finding the xPath for a particular line within a node that contains more than one line of text

My HTML code resembles the following structure:

<div class='textContainer'>
    <div class='textLabel'> </div>
    <div class='text'> 
    "First Line of text" 
    "Second Line of text" 
    "Third line of text" 
    </div>
</div>

I have successfully created a locator to identify the node containing the text. However, my challenge now is to perform an assertion specifically on the first and third lines of text. Therefore, I require unique locators for those particular lines.

  • //div[@class='text']/text[1]
  • //div[@class='text']/text[3]

Is it feasible to achieve this task?

Your assistance on this matter would be highly appreciated.

Thank you in advance!

Answer №1

If you want to achieve this using XPath 2 or 3, for example in a web browser or Node.js with Saxon-JS 2, which supports XPath 3.1:

const lines = SaxonJS.XPath.evaluate(`//div[@class = 'text']/tokenize(., '\n')[normalize-space()]!normalize-space()`, document, { xpathDefaultNamespace : 'http://www.w3.org/1999/xhtml' });

console.log(lines);
console.log(lines[0]);
<script src="https://www.saxonica.com/saxon-js/documentation/SaxonJS/SaxonJS2.rt.js"></script>

<div class='textContainer'>
    <div class='textLabel'> </div>
    <div class='text'> 
    "First Line of text" 
    "Second Line of text" 
    "Third line of text" 
    </div>
</div>

It is important to note that in any version of XPath or the DOM, the normalized tree consists of a single text node. However, in XPath 2 or later, you have the ability to split or tokenize the string of a text node into sequences of strings and process each string individually. The Saxon-JS 2 API for JavaScript conveniently returns this XPath 3.1 string sequence as a string array in JavaScript.

In the context of the XPath 2 or 3 data model, the path expression

//div[@class = 'text']/tokenize(., '\n')[normalize-space()]!normalize-space()
provides a sequence of strings that can be accessed by index numbers as typically done in XPath. Therefore,
let $lines := //div[@class = 'text']/tokenize(., '\n')[normalize-space()]!normalize-space() return $lines[2]
will retrieve the second item or string in the sequence of normalized text lines within the text node.

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

"Customizing the website's font: A step-by-step guide to replacing the default Roboto font with a custom font

Despite my efforts to globally override the font, I am still encountering instances where the Roboto font is not being replaced, particularly on MUI select and autocomplete components. import { createTheme } from '@material-ui/core/styles'; // A ...

How to integrate a chips feature in Angular 4 using Typescript

Struggling to incorporate a chips component into my Angular web application, which comprises Typescript, HTML, and CSS files. After grappling with this for weeks without success, I have yet to find the right solution. To review my current code, you can a ...

Tips for altering the color of a specific row in JQuery by targeting its unique id

I've been struggling to accomplish a simple task using Jquery and CSS, but I seem to be stuck. My issue involves making an ajax request to update a PostgreSQL table and retrieve an id in return. This id corresponds to the id of a row in a previously ...

What is the best method to update numerous low-resolution image sources with higher resolution images once they have finished loading?

I'm currently developing a website that implements a strategy of loading low-resolution images first, and then swapping them for high-resolution versions once they are fully loaded. By doing this, we aim to speed up the initial loading time by display ...

What is the maximum allowable size for scripts with the type text/json?

I have been attempting to load a JSON string within a script tag with the type text/json, which will be extracted in JavaScript using the script tag Id and converted into a JavaScript Object. In certain scenarios, when dealing with very large data sizes, ...

By incorporating JavaScript, clicking on an image will trigger a shift in the position of a different element

Just starting out with JavaScript and experimenting with creating an event where clicking on an image triggers the movement of another hidden image. The hidden image is positioned off-screen to the left, while there is a table of images in the center of th ...

Engaging Floor Layout

Currently, I am in the process of developing an interactive floorplan for an office project. The main objective is to provide a user-friendly interface where individuals can search for a specific employee and have their respective office location highlight ...

Tips for Excluding Content Retrieved Through file_get_contents?

Currently, I am storing the source code of a webpage in a variable called $html using the following line: $html = file_get_contents('http://www.google.com'); When I use <textarea><?php echo htmlentities($html); ?></textarea> ...

What are the steps to personalize Twitter Bootstrap with Less for changing the height of the Navbar?

I recently stumbled upon some interesting articles that explain how to customize various elements of Twitter Bootstrap using LESS. You can check out one of the articles here and find more information about Twitter Bootstrap here. However, I am still unsure ...

I am puzzled as to why I keep receiving the error message "Cannot read property 'poPanel' of undefined"

CSS In my project, I am implementing a feature that displays an ordered list by looping through an array of objects and adding them on a button click. It works smoothly for adding items, but when I try to implement a remove function to delete each item, I ...

Design a custom Bootstrap dropdown using an input[type="text"] element

After exploring the Bootstrap dropdown example here, I realized that for my particular scenario, it would be more beneficial to have an input field (type="text") instead of a button. This way, I can display the selected option from the dropdown. Is there ...

Determine whether a WebElement contains a particular content within the :after pseudo class

After locating my element in Selenium, I've come across an interesting challenge. IWebElement icon = box.FindElement(By.ClassName("box-icon")); Sometimes, this element (icon) has a content set as follows: &:after { content: $icon-specia ...

Having trouble making my if / else statement show the_header_image_tag on WordPress

Having some trouble getting my if / else statement to function correctly. I am using a WordPress function called '' and I want to apply different CSS styles based on whether it is used or not. My theme allows for the display of a banner, but onl ...

Angular Material: Enhanced search input with a universal clear button

After searching for a cross-browser search control with a clear button similar to HTML5, I found the solution rendered by Chrome: <input type="search> The code that gave me the most relevant results can be found here. I used the standard sample w ...

Display a dropdown menu when clicking on a close button in a single element using Vanilla JavaScript

I'm currently in the process of learning Javascript and trying to grasp the concept of events and selectors. My aim is to have a close button that, when clicked, triggers a specific dropdown related to the card it's attached to. I plan to achie ...

What is the method for selecting the "save as" option while downloading a file?

Imagine a scenario where you click on a link like this: <a href="1.txt">Download</a> After clicking the link, a save as window will appear. Is it feasible to utilize JavaScript in order to simulate button clicks within that window? Alternativ ...

How does JQuery handle color parsing in text?

Is there a way to automatically parse colors in text and apply them to CSS? For instance, if I type #40464f, I want the color to be caught and included in some CSS styles. I am familiar with how to achieve this by adding markup: <span data-color=""> ...

Validation of Single Fields in Angular Reactive Forms

When I validate a reactive form in Angular, I expect the error message to show up beneath the invalid field whenever incorrect data is entered. <form (ngSubmit)=sendQuery() [formGroup]="form"> <div *ngFor='let key of modelKeys&ap ...

Is there a way to connect a CSS external file that is saved on Dropbox?

Is it possible to link an external CSS file stored in Dropbox with HTML? I have followed all the instructions I could find online, including clicking and pressing "Copy Dropbox Link" to generate an href link. However, it doesn't seem to be working. ...

What is the term for the visual display of a product through a photo gallery or slideshow?

Can someone help me identify what the item I'm looking for? You can click on the link to see an example of the product: sephora product example What is the technical term for the section that contains product pictures and slides? Are there any librar ...