Reputation: 225
I am using Selenium and Java to write a test, below is my DOM:
<body>
<div class='t'><span>1</span></div>
<div class='t'></div>
<div class='t'><span>2</span></div>
<div class='t'><span>3</span></div>
<div class='t'><span>4</span></div>
<div class='t'><span>5</span></div>
<div class='t'><span>6</span></div>
<div class='t'><span>7</span></div>
<div class='tt'></div>
</body>
when I use: //div[@class='t'][last()]
I get:
<div class="t"><span>7</span></div>
but when I use: //div[@class='t' and last()]
I get:
<div class="t"><span>1</span></div>
<div class="t"/>
<div class="t"><span>2</span></div>
<div class="t"><span>3</span></div>
<div class="t"><span>4</span></div>
<div class="t"><span>5</span></div>
<div class="t"><span>6</span></div>
<div class="t"><span>7</span></div>
it's like last()
is not applied to the second xpath, why?
Upvotes: 2
Views: 143
Reputation: 5113
//div[@class='t'][last()]
... means pick the element from the list of matches (where @class='t'
) whose index is last, which is what you want.
With //div[@class='t' and last()]
, the already-calculated value of last()
is applied for each match in the list purely on the basis of being != 0, and it will cause the div
matcher to return FALSE only if last()
is zero. In other words, the last()
does not get used to select a single node from the list. That's definitely not what you want.
For example: if last()
evaluates to 5, //div[@class='t' and 5]
will return every matching element in the list because 5 != 0.
The net result is that if any nodes are matched (last()
> 0), all of them will be returned.
See also: XSLT getting last element
Upvotes: 3