'Get list of elements with class name in javascript with selenium
How can I get a list of elements with a certain class name in javascript with selenium?
I am searching for any elements with the class message_body. I want a array containing all of the elements that have that class.
driver.findElements(By.className("message_body")) doesn't work, it seems to return something else.
How can I get this list?
Solution 1:[1]
Here is an example to get the text from a list of elements:
driver.findElements(By.className("message_body")).then(function(elements){
elements.forEach(function (element) {
element.getText().then(function(text){
console.log(text);
});
});
});
Solution 2:[2]
So, I'm using an older version of Selenium, v2.47.1, but something I used when driver.findElements(By.className("someClass")) wasn't sufficient was driver.findElements(By.xpath("/path/to/[@class='someClass']")) . This will return a List<WebElement>. If I remember correctly, By.xpath is a little slower than some of the other options on some browsers, but not by a whole lot....
Solution 3:[3]
First you need to get the elements collection:
public async getInstalledApps(): Promise<any[]> {
const appsList: WebComponent = this.browser.find(By.css(`div .icons__title`));
return await appsList.getElements();
}
Then, using the function above you can do anything, for example get the text property and save them. For example if it's a group of Apps button and you want to get a names array of them:
public async getInstalledAppsList(): Promise<string[]> {
const appsList: string[] = [];
let app: string = '';
(await this.getInstalledApps()).forEach(async element => {
await Promise.resolve(element).then(async (text: any) => {
app = await (await text.getText());
appsList.push(app);
});
});
return appsList;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Florent B. |
| Solution 2 | Tyler |
| Solution 3 | Vict01 |
