Unable to find the <a> element with a numerical id attribute in Playwright. The selector '#56' is not recognized as valid

Seeking to identify and target the <a> element with an id attribute. Attributes that may be used:

  • role
  • href
  • title
  • id
  • style
  • onclick

I am able to do so using role and name, but unsuccessful with id or onclick. The latter two would be beneficial for future tasks.

Clicking on the locator identified by role and name works smoothly:

point56Button = this.page.getByRole('button', {
    name: 'Pole 56',
    exact: true,
  });

However, attempting to do it by id generates an error:

Error: locator.click: DOMException: Failed to execute 'querySelectorAll' on 'Document': '#56' is not a valid selector.
    at query (<anonymous>:3329:41)
    ...

Snippet of website code:

<a role="button" href="#" title="Pole 56" id="56" style="width:104px;height:16px;top:611px;left:668px;text-align:Right;vertical-align:text-bottom;position:absolute;cursor:pointer;padding-top:71px;font-size:13px;color:black;" onclick="RunSubwizard('56',event);"></a>

My code snippet to locate an element by id:

point56Button = this.page.locator('#56');

Objective is to click on the element located by id

Expected outcome: open wizard

Successful in locating elements by role and name Unsuccessful in locating elements by id

Answer №1

Here's how it works for me:

Identifying the HTML element

<a role="button" href="#" title="Pole 56" id="56" style="width:104px;height:16px;cursor:pointer" onclick="RunSubwizard('56',event);"></a> 

Using locator to achieve this

point56Button = this.page.locator('a[id="56"]');

Answer №2

Although the focus is not on Playwright, the information provided here can still be valuable. The issue with the CSS selector error arises within the realm of pure browser code:

document.querySelector("#56");
  // => SyntaxError: Document.querySelector: '#56' is not a valid selector
<a id="56"></a>

To work around this problem when dealing with numeric IDs, you can utilize an attribute selector:

console.log(document.querySelector('[id="56"]'));
<a id="56"></a>

If it's not immediately clear, the Playwright locator for this scenario would be

this.page.locator('a[id="56"]');
.

For more information, refer to: How to select an element that has an ID which begins with a digit?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

VS Code failing to detect Angular, inundated with errors despite successful compilation

Having some issues with loading my angular project in vscode. It used to work fine, but suddenly I'm getting errors throughout the project. I have all the necessary extensions and Angular installed. https://i.stack.imgur.com/qQqso.png Tried troubles ...

What is the best way to retrieve the previous URL in Angular after the current URL has been refreshed or changed

Imagine being on the current URL of http://localhost:4200/#/transactions/overview/5?tab=2 and then navigating to http://localhost:4200/#/deals/detail/ If I refresh the deals/detail page, I want to return to the previous URL which could be something like h ...

Screen a roster for shared elements with another roster

Within my dataset, I am working with a List of Objects that adhere to the following Model structure: export class Animal{ public aniId: number; public aniName: string; } export Class Zoo{ public id: number; public name:string; public aniId: number ...

Defining and initializing variables in TypeScript

Trying to get the hang of Angular and TypeScript, but I'm stuck on why I can't access my variable after declaring it. It looks something like this. export class aComponent implements OnInit { num : Number; num = currentUser.Id Encounterin ...

React Material-UI is notorious for its sluggish performance

I recently started using React Material-ui for the first time. Whenever I run yarn start in my react app, it takes quite a while (approximately 25 seconds) on my setup with an i5 8400 + 16 GB RAM. Initially, I suspected that the delay might be caused by e ...

Errors occur when trying to utilize an enum as a generic type in Typescript that are not compatible

Take a look at the code snippet provided. The concept here is that I have different provider implementations that extend a base provider. Each provider requires a settings object that is an extension of a base settings object. Additionally, each provider c ...

Having trouble retrieving spot price using Uniswap SDK due to a transaction error LOK

const quotedAmountOut = await quoterContract.callStatic.quoteExactInputSingle( immutables.token0, immutables.token1, immutables.fee, amountIn, 0 ) I set up a pool on Uniswap V3 for two ERC20 dummy tokens by using the createPool() met ...

Does anyone have experience using the useRef hook in React?

Can someone help me with this recurring issue: "Property 'value' does not exist on type 'never'" interface InputProps { name: string; icon?: ReactElement; placeholder?: string; } const Input = ({ name, icon: Icon, ...rest }: Inpu ...

Closing a tab in another part of the session using Typescript and Angular

Looking for a solution on how to close a tab within an Angular session that was opened from somewhere else in the same session. For instance: In Component A this.window = this.windowToken.open('Some URL', 'Some Tab Name', 'Some ...

I am having trouble viewing the input value on my Angular5 form

Here is the HTML code snippet that I've written: <input type="text" name="fechainscripcion" #fechainscripcion="ngModel" [(ngModel)]="alumno.fechainscripcion" value="{{today | date:'dd/MM/yyyy'}}" class="form-control" /> This is a seg ...

Unable to pass response from httpclient post method to another custom function in Angular 4

I've implemented the addUser(newUser) function in my sign-in.service.ts file like this: addUser(newUser) { const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; let body = JS ...

Unable to refresh the context following a successful API call

My current project in NextJS requires a simple login function, and I have been attempting to implement it using the Context API to store user data. However, I am facing an issue where the context is not updating properly after fetching data from the back-e ...

updating rows in a table

Currently, I have a grid array filled with default data retrieved from the database. This data is then displayed on the front end in a table/grid format allowing users to add and delete rows. When a row is added, I only want to insert an empty object. The ...

Adjust puppeteer window dimensions when running in non-headless mode (not viewport)

Is there a way to adjust the browser window size to match the viewport size in Chrome(ium)? When only setting the viewport, the browser can look awkward if it is not running headfully and I want to visually monitor what's happening within the browser ...

Creating dynamic components in ReactJS allows for versatile and customizable user interfaces. By passing

Within the DataGridCell component, I am trying to implement a feature that allows me to specify which component should be used to render the content of the cell. Additionally, I need to pass props into this component. Below is my simplified attempt at achi ...

Guide to highlighting manually selected months in the monthpicker by utilizing the DoCheck function in Angular

I'm facing an issue and I could really use some assistance. The problem seems quite straightforward, but I've hit a roadblock. I have even created a stackblitz to showcase the problem, but let me explain it first. So, I've developed my own t ...

Creating a Node.js asynchronous setup function

I'm in the process of transitioning from Nodejs v12 to v14 and I've noticed that v14 no longer waits for the setup function to resolve. My setup involves Nodejs combined with Express. Here's a simplified version of my code: setup().then(cont ...

What is the best approach to managing a 204 status in Typescript in conjunction with the Fetch API

Struggling to handle a 204 status response in my post request using fetch and typescript. I've attempted to return a promise with a null value, but it's not working as expected. postRequest = async <T>(url: string, body: any): Promise ...

Implementing reCaptcha on React Native: A Step-by-Step Guide

Currently, I am in the process of integrating a reCaptcha validator into a login screen for a react-native application that needs to function seamlessly on both web and mobile platforms. Despite being relatively new to programming and lacking experience w ...

Removing punctuation from time duration using Moment.js duration format can be achieved through a simple process

Currently, I am utilizing the moment duration format library to calculate the total duration of time. It is working as expected, but a slight issue arises when the time duration exceeds 4 digits - it automatically adds a comma in the hours section (similar ...