I’m trying to highlight a specific word within a sentence using Playwright.
For example, given the text:
"when will my account be ready?"
I only want to highlight the word "account" and then right-click on it.
The element looks like this:
<div class="line-text">when will my account be ready</div>
I’ve tried using selectors, but can’t figure out how to highlight just that one word. Is there a way in Playwright to select or highlight a substring inside an element, not the whole text?
Playwright doesn’t have a built-in API to select partial text directly, but you can do it using the browser’s native window.getSelection() API through page.evaluate():
await page.evaluate("""
const element = document.querySelector('.line-text');
const range = document.createRange();
const textNode = element.firstChild;
const start = textNode.textContent.indexOf('account');
const end = start + 'account'.length;
range.setStart(textNode, start);
range.setEnd(textNode, end);
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
""")
This script programmatically highlights just the word “account” on the page.
You can then trigger a right-click event:
await page.mouse.click(100, 200, button=“right”)Preformatted text
If you only need to right-click (not visually highlight), locate the substring’s bounding box using JavaScript and simulate the click:
box = await page.evaluate_handle("""
() => {
const el = document.querySelector('.line-text');
const text = el.textContent;
const idx = text.indexOf('account');
const range = document.createRange();
const node = el.firstChild;
range.setStart(node, idx);
range.setEnd(node, idx + 'account'.length);
const rect = range.getBoundingClientRect();
return { x: rect.x + rect.width/2, y: rect.y + rect.height/2 };
}
""")
coords = await box.json_value()
await page.mouse.click(coords["x"], coords["y"], button="right")
This approach lets you interact precisely with the substring region.
If you can modify the DOM or test data, wrap the word “account” in a span:
<div class="line-text">when will my <span class="target">account</span> be ready?</div>
Then simply use:
await page.locator('.target').click(button='right')
This is often the cleanest solution when you control the test markup, avoids the need for custom JS or selection logic.