Skip to content
CodeKruPro

Select Element by Text Content

5/70

Select Element by Text Content

Playwright's getByText() finds elements by their visible text content. This is one of Playwright's recommended locators because it matches what users actually see.

To read an attribute like href, use locator.getAttribute('href') (same method as the previous exercise).

Locators do not have a tag-name helper. To run a small function on the real DOM node, use locator.evaluate():

Example: const id = await element.evaluate(el => el.id); runs the arrow function on the matched element and returns its id.

On the Links page, there is a link with text: Go to Homepage. Its href is the relative path /, and getAttribute() returns the attribute exactly as written in the HTML.

Task:

  1. Navigate to https://testkru.com/Elements/Links
  2. Find the link by its visible text with page.getByText()
  3. Read its href attribute with getAttribute()
  4. Print the element's tag name in lower case, read inside locator.evaluate() from the DOM node's tagName

Expected output:

Tag: a
Href: /