williamtell
williamtell

Reputation: 301

Having trouble with getAttribute for a WebElement

I am trying to get the attribute of an element. It was working fine but suddenly it is not. Not sure if I changed something.

Error:

TypeError: Cannot read property 'info' of undefined

Method 1:

async getElementAttribute12(webElement: WebElement, whichAttribute: string): Promise<string> {
        try {
            let attribute = '';
            await webElement.getAttribute(whichAttribute).then(async function(attr) {
                await this.info('attr: ', attr);
                attribute = attr;
            });
            return attribute;
        } catch (error) {
            fail(`Get attribute error. ${error}`);
        }
    }

Method 2:

After checking if the element is present. I think this will be a better approach. Inputs are welcome.

    async getElementAttribute(webElement: WebElement, whichAttribute: string): Promise<string> {
        try {
            let attribute = '';
            if (await browser.isElementPresent(webElement)) {
                await webElement.getAttribute(whichAttribute).then(async function(attr) {
                    await this.info('attr: ', attr);
                    attribute = attr;
                });
                return attribute;
            }

        } catch (error) {
            fail(`Get attribute error. ${error}`);
        }
    }

Upvotes: 0

Views: 99

Answers (1)

Dmitriy
Dmitriy

Reputation: 2822

The problem here is that your this refers to the wrong thing, you need to use an arrow function here:

await webElement.getAttribute(whichAttribute).then(async (attr) => {

Upvotes: 1

Related Questions