Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to identify the nth sub element using xpath?
We can identify the nth sub element using xpath in the following ways:
By adding square brackets with index.
By using position() method in xpath.
Method 1: Using Square Brackets with Index
The most common approach is to add square brackets with the desired index number after the element selector:
// Select the 2nd div element //div[2] // Select the 3rd li element inside ul //ul/li[3] // Select the first input with type='text' //input[@type='text'][1]
Method 2: Using position() Function
The position() function provides another way to target elements by their position:
// Select the first element with type text using position() //input[@type='text'][position()=1] // Select the 3rd paragraph //p[position()=3] // Select the last element //div[position()=last()]
JavaScript Example: Targeting nth Elements
<!DOCTYPE html>
<html>
<head>
<title>XPath nth Element Example</title>
</head>
<body>
<ul id="myList">
<li>First Item</li>
<li>Second Item</li>
<li>Third Item</li>
<li>Fourth Item</li>
</ul>
<div>
<input type="text" placeholder="Input 1">
<input type="text" placeholder="Input 2">
<input type="text" placeholder="Input 3">
</div>
<script>
// Function to get element by XPath
function getElementByXPath(xpath) {
return document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
}
// Select 2nd li element using index
let secondLi = getElementByXPath("//ul/li[2]");
console.log("Second li text:", secondLi.textContent);
// Select 3rd input using position()
let thirdInput = getElementByXPath("//input[position()=3]");
console.log("Third input placeholder:", thirdInput.placeholder);
// Select first text input
let firstTextInput = getElementByXPath("//input[@type='text'][1]");
console.log("First input placeholder:", firstTextInput.placeholder);
</script>
</body>
</html>
Second li text: Second Item Third input placeholder: Input 3 First input placeholder: Input 1
Comparison
| Method | Syntax | Use Case |
|---|---|---|
| Square Brackets | //element[n] |
Simple index-based selection |
| position() Function | //element[position()=n] |
More complex positioning logic |
Key Points
XPath indexing starts from 1, not 0
Use
[last()]to select the last elementUse
[last()-1]to select the second-to-last elementposition() function is more flexible for complex conditions
Conclusion
Both square brackets and position() function effectively target nth elements in XPath. Square brackets are simpler for basic indexing, while position() offers more flexibility for complex selections.
