user5458362
user5458362

Reputation:

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?

Upvotes: 2

Views: 19341

Answers (3)

Vict01
Vict01

Reputation: 308

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;
}

Upvotes: 0

Tyler
Tyler

Reputation: 197

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....

Upvotes: 1

Florent B.
Florent B.

Reputation: 42518

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);
        });
    });
});

Upvotes: 6

Related Questions