2

I am trying to quickly find a specific node using XPath but it seems my multiple predicates are not working. The div I need has a specific class, but there are 3 others that have it. I want to select the fourth one so I did the following:

//div[@class='myCLass' and 4]

However the "4" is being ignored. Any help? I am new to XPath.

Thanks.

3 Answers 3

3

If a xpath query returns a node set you can always use the [OFFSET] operator to access a certain element of it.

Use the following query to access the fourth element that matches the @class='myClass' predicate:

//div[@class='myCLass'][4]

@WilliamNarmontas answer might be an alternative to the syntax showed above.

Sign up to request clarification or add additional context in comments.

Comments

3

Alternatively,

//div[@class='myCLass' and position()=4]

Comments

3

The accepted answer works correctly only if all of the div elements have the same parent. Otherwise use:

(//div[@class='myCLass'])[4]

1 Comment

Hi @TheGateKeeper, I'd like to second the above answer and give it an alternative shape, a bit longer but IMHO more readable: /descendant::div[@class eq 'myClass'][4].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.