I'm trying to get a property value of web element, setting property name dynamically.
Each time, when I use square brackets property accessor (Ex: node[propertyName]
), I get an error "elementHandle.evaluate: ReferenceError: propertyName is not defined".
But if I try the same property, using dot property accessor, it works fine and I get expected value.
The documentation of class JSHandle
and method evaluate
is here.
I tried to reproduce the same steps in Browser console.
const elements = $$("thead th");
const element = elements[0];
propertyName = "innerText";
const propertyValue2 = element.innerText;
const propertyValue = element[propertyName];
console.log(propertyValue2); // Expected property value
console.log(propertyValue); // Expected property value
But in my IDE, a got a little bit other results:
protected async getElementProperty(): Promise<string> {
const elements = await this.page.$$("thead th");
const element: JSHandle = elements[0];
propertyName = "innerText";
const propertyValue1: string = await element.evaluate((node) => node.innerText); // Expected property value
const propertyValue2: string = await element.evaluate((node) => node[propertyName]); // ReferenceError: propertyName is not defined
const propertyValue3: string = await element.evaluate(`(node) => node[${propertyName}]`); // Undefined
return propertyValue;
}