Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add set/getAttribute to element #123

Merged
merged 1 commit into from
May 2, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions src/element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -352,4 +352,38 @@ export class Element {
this.#protocol.notifications.delete(method2);
}
}

/**
* Get an attribute on the element
*
* @example
* ```js
* const class = await elem.getAttribute("class"); // "form-control button"
* ```
*
* @param name - The name of the attribute
*
* @returns The attribute value
*/
public async getAttribute(name: string): Promise<string> {
return await this.#page.evaluate(
`${this.#method}('${this.#selector}').getAttribute('${name}')`,
);
}
/**
* Set an attribute on the element
*
* @example
* ```js
* await elem.setAttribute("data-name", "Sinco");
* ```
*
* @param name - The name of the attribute
* @param value - The value to set the atrribute to
*/
public async setAttribute(name: string, value: string): Promise<void> {
await this.#page.evaluate(
`${this.#method}('${this.#selector}').setAttribute('${name}', '${value}')`,
);
}
}
25 changes: 25 additions & 0 deletions tests/unit/element_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,5 +154,30 @@ for (const browserItem of browserList) {
});
});
});

await t.step("getAttribute()", async (t) => {
await t.step("Should get the attribute", async () => {
const { browser, page } = await buildFor(browserItem.name);
await page.location("https://drash.land");
const elem = await page.querySelector("a");
const val = await elem.getAttribute("href");
await browser.close();
assertEquals(val, "https://github.com/drashland");
});
});

await t.step("setAttribute()", async (t) => {
await t.step("Should set the attribute", async () => {
const { browser, page } = await buildFor(browserItem.name);
await page.location("https://drash.land");
const elem = await page.querySelector("a");
elem.setAttribute("data-name", "Sinco");
const val = await page.evaluate(() => {
return document.querySelector("a")?.getAttribute("data-name");
});
await browser.close();
assertEquals(val, "Sinco");
});
});
});
}