Home > Software design >  Playwright - Select element based on CSS property
Playwright - Select element based on CSS property

Time:11-21

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.

CodePudding user response:

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>

  • Related