Skip to content
CodeKruPro

Select Element by CSS Class and Tag

7/70

Select Element by CSS Class and Tag

CSS selectors in Playwright work just like in the browser:

  • .className — find by class
  • tag.className — find by tag with class
  • tag#id — find by tag with ID

Read the text inside an element with locator.textContent().

Example: const text = await page.locator('p.note').textContent(); reads the text of the paragraph with the class note.

On the Text Messages page, there is a bold text element with ID boldText. The #plainText element has spaces around its text in the HTML, so call .trim() on the result.

Task:

  1. Navigate to https://testkru.com/Elements/TextMessages
  2. Find the element using CSS selector #boldText
  3. Print its text content using textContent()
  4. Find the element using CSS selector #plainText
  5. Print its text content using textContent(), trimmed with .trim()

Expected output:

Bold: A Bold Text
Plain: A Plain Text