2

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?

3
  • What does it seem to return? And what kind of array are you looking for? (Can you show the assignment you make with driver.findElements(By.className("message_body"))? Commented May 4, 2016 at 16:44
  • @Tyler I am not sure. Another SO answer said it returns a promise, but I don't know what that means. Commented May 4, 2016 at 16:44
  • Which version of Selenium are you using? Commented May 4, 2016 at 16:48

3 Answers 3

6

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);
        });
    });
});
Sign up to request clarification or add additional context in comments.

Comments

1

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

3 Comments

This is javascript, so I don't think a List<WebElement> will be returned, but this might work.
Sorry, this doesn't work. It gives driver.findElements is not a function.
Oh! I misread that as java -- this is a java function. Sorry about that.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.