How can I create a locator from a link with a unique href in Playwright?

I was recently asking myself this very same questions. With all the great locator tooling out there, sometimes there is just an old piece of legacy code that isn't going to get modified to add a data test id or other unique locator. In those situations we can utilize CSS selectors!

The HTML in question is provided below. The only unique value I could find was the href value for this link. With this webpage, depending on the API calls the notification span may or may not be present, and the number 100 could be any number.

<li class="nav-item">
  <a class="nav-link" href="#/admin/messages">
    <i class="fa fa-inbox" style="font-size: 1.5rem;">
      <span class="notification">100</span>

I wanted to create a test that would validate the span inside the link had the correct count I was expecting. My solution was to utilize the CSS Attribute selector in the page.locator(). In the below example I first locate the higher level link <a> tag, by the href, assigned that to a variable named messageLink and then set a new variable messageCountSpan and used the messageLink locator using chaining, getting the span inside the link and returning that as a locator.

const messageLink = page.locator('[href*="#/admin/messages"]')
const messageCountSpan = messageLink.locator("span");

await expect(messageCountSpan).toHaveText(`${count}`);

A few other helpful resources that helped me on my own learning journey.

PlayWright - Selecting link with nth-match and value in href
I have a page, where I need to select a link. The links on the page are (for example):&lt;a href=&quot;/animation?ID=11111\&amp;amp;model\_id=AAAAA&quot;&gt;Preview Results&lt;/a&gt;&lt;a href=&q...
Selectors Level 4
CSS attribute selector does not work a href
I need to use attribute selector in css to change link on different color and image, but it does not work. I have this html: &lt;a href=”/manual.pdf”&gt;A PDF File&lt;/a&gt; And this css: a { ...

Thanks for reading! If you found this helpful, reach out and let me know on LinkedIn or consider buying me a cup of coffee. If you want more content delivered to you in your inbox subscribe below.