Ania David Ania David - 10 months ago 22
HTML Question

How to take xpath if the element sometimes have an extra class name?

my element is :

<div class="class1 class2">

but in some cases, there is an extra class like this:

<div class="class1 class2 fixClassCustom">

how can I handle that in xpath

i used to do this:

.//div[@class="class1 class2"]

but how can i handle both situations ?


You can use contains() and concat():

.//div[contains(concat(' ',@class,' '), ' class1 ') and 
       contains(concat(' ',@class,' '), ' class2 ')]

Note that concat() helps to avoid false positives - for instance, the expression would not match <div class="class10 class20"> case while the //div[contains(@class, 'class1') and contains(@class, 'class2')] expression that does not use concat() would match the element.