12

I want to write an xpath to identify a div which has the class foo and the display: block. I wrote

div[@class="foo" and @style="*display: block*"]

but it doesn't work. Is it correct to use and? is it correct to use asterisks like in regex expressions?

1 Answer 1

22

your xpath is searching for @style="*display: block*", it means totally equal to value inside quotes. Use contains() instead, Fyi: there's also starts-with() method

//div[@class='foo'][contains(@style,'display: block')]

There's an issue with using such locator, as sometimes element is visible, though there's no style display:block. So you can use similar locator, but instead of containing block, searche for not-containing "none" (as in display:none), can try it by adding this to main locator [not(contains(@style, 'none'))]. Just remember about such option)

4
  • 1
    Is there any difference to //div[@class='foo' and contains(@style, 'display: block')] ?
    – CodeManX
    Commented Jul 6, 2017 at 8:46
  • no) i just prefer not to use 'and' , as it's more text, but both are correct) Commented Jul 6, 2017 at 8:47
  • 1
    there's an issue with using such locator, as sometimes element is visible, though there's no style block. So once i used totally similar locator, but instead of containing block i searched for not-containing "none" (as in display:none), can try it by adding this to main locator [not(contains(@style, 'none'))]. Just remember about such option) Commented Jul 6, 2017 at 8:55
  • @VitaliyMoskalyuk: At least on a German keyboard ` and ` is way easier to type than square brackets (Alt Gr + 8, Alt Gr + 9). I believe that's one reason why some German programmers use English keyboards / keyboard layouts ;)
    – CodeManX
    Commented Jul 26, 2017 at 21:35

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.