Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Playwright – Select element based on CSS property

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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.

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading