How do I use Playwright to verify if a specific string is present in an h1 element?


Checking if an h1 Element Contains a Specific String with Playwright

First, you need to locate the h1 element. You can use Playwright's page.locator() method with a CSS selector that matches the h1 element. Let's say your h1 element has an id of "title". Here's how you can locate it:

const titleElement = await page.locator('#title');

Next, get the text content of the h1 element using locator.textContent(). This returns a Promise that resolves to a string containing all the text within the h1 element.

const titleText = await titleElement.textContent();

Finally, check if the text contains "hello, world" using JavaScript's String.prototype.includes() method. This method returns true if the specified substring is found within the string.

if (titleText.includes('hello, world')) {
  console.log('The title contains "hello, world"!');
} else {
  console.log('The title does not contain "hello, world".');

So, to check if an h1 element includes a string "hello, world" using Playwright, you:

  1. Locate the h1 element using page.locator()
  2. Get its text content using locator.textContent()
  3. Use String.prototype.includes() to check for the presence of the desired substring.

For more insights on using Playwright, check out Understanding the Difference Between Locators and Selectors in @playwright/test.


Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

Related Questions

AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.