← Back to Discord Forum

Scope page to a specific div

Hi, I have a page that has left side bar, right side bar, header, footer, and content. I have a bunch of tests that were written before we had this page. They assumed the only thing on the screen would be the content section. Is there any way I can scope "page" to just that div? Otherwise I'll either have to pass page and locator to everything or have everything do the initial page.getByTestId("content") then and the actual query. thanks

This thread is trying to answer question "Is there any way I can scope 'page' to just the content div?"

6 replies

Hi! you can add a base Page to all pages, with the sections (header, footer....) It was not clear to me why do you need some scope to only content. Are you using some relative locators to content? like page.getByTestId("content").getByTestId("button") because most of the time relative locator to parent locator is not a good practice

@apis3445 I see. well, there's a lot of dynamic stuff going on and yea, sometimes there is more than one button with the same testId in the different sections. I'm certainly open to suggestions. thanks

If there are same testids and you can't request unique ids you need to use the section to get the locator that you need


In that case try using locator chaining or method like first(), last(), nth()

you might want to look into fixtures

@tallyb Yes, looks like fixtures might be the way to go but it's awefully heavy handed way to expose just one property i.e. the locator for the section of the page.


Scoping 'Page' to a Specific Div with Playwright

Yes, you can! Playwright's page.$$eval() method lets you query elements within a specific div. This method finds all elements matching a selector and passes them as an array to a page function.

Here's how you can do it:

const divElements = await page.$$eval('#myDiv', (divs) => {
  // Perform operations or extract information from 'divs'
  // Return any desired result

In this example, #myDiv is the selector for the div you're targeting. The array of matched elements is passed to your page function (divs) => { ... }, where you can perform operations or extract information.

This approach lets you focus your actions and assertions on elements within a specific div, giving you more control when interacting with your web application.

Remember, if multiple elements match the selector, only the first one is used by default. If you need to work with multiple matching elements, adjust your code accordingly.

Happy testing with Playwright! Let me know if there's anything else you need help with.

Related Discord Threads

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.