2

I need to select the appropriate element with Playwright by filtering based on CSS properties. In my particular case, I need to filter out the elements that have the text-decoration:line-through property and focus on the rest of them.

Here is the DOM with the elements:

DOM elements

<span>
    <span style="line-height:1.15 !important;display:initial;text-decoration:line-through;display:block;">0.42</span>
    <span style="line-height:1.15 !important;display:initial;font-weight:bold;">0.29</span>
</span>

(Terrible HTML code, I know... There is not much I can do about that though...)

In this case, I need to select the 2nd span, which is missing the strike-though style, but the order and number of span elements could not be anticipated.

Is there a way to do this with a single ilocator.Locator(selector); query? I need to do it with a single query, because the code I create needs to be generic and not assume things and do "manual" filtering. Everything needs to be in the selector.

user2173353
  • 4,316
  • 4
  • 47
  • 79

1 Answers1

4

You can use the contain operator "*=". it should be something akin to:

page.locator('span[style*="text-decoration:line-through"]')

Demo in CSS:

span {
  color: orange;
}

/* target span with line-through */
span[style*="text-decoration:line-through"],
/* handle white space */
span[style*="text-decoration: line-through"] {
  color: blue;
}

/* target span without line-through */
span:not([style*="text-decoration:line-through"]),
/* handle white space */
span:not([style*="text-decoration: line-through"]) {
  color: red;
}
<span>
  <span style="stuff">a</span>
  <span style="stuff; text-decoration:line-through; foo">b</span>
</span>
aloisdg
  • 22,270
  • 6
  • 85
  • 105
  • This is interesting, because I have not thought of this, but there are two problems: 1) this includes the elements I want filtered out instead of excluding them and 2) there could be issues with spaces around the `:` character. In theory it could work though. I could instead use the `font-weight:bold` as part of the selector to solve the 1st problem and hope nothing changes in the spaces for the 2nd one. – user2173353 Nov 20 '22 at 23:32
  • @user2173353 edit to handle include/exclude and an example to handle a space after like `: ` – aloisdg Nov 20 '22 at 23:37
  • Thanks. This should work. Initially, I was hoping there was something that was not relying on text-matching, but perhaps this is good enough. :) – user2173353 Nov 20 '22 at 23:48