How to retrieve a list of elements based on their class name using JavaScript and Selenium

Is there a way to retrieve a list of elements using a specific class name in JavaScript with Selenium?

I am specifically looking for elements that have the class message_body. I need an array that includes all elements with this class.

Unfortunately,

driver.findElements(By.className("message_body"))
is not yielding the expected results. It seems to be returning something different.

What alternative method can I use to obtain this desired list of elements?

Answer №1

Provided below is an illustration on extracting text from a group of elements:

driver.findElements(By.className("message_body")).then(function(elements){
    elements.forEach(function (element) {
        element.getText().then(function(text){
            console.log(text);
        });
    });
});

Answer №2

When working with an older version of Selenium, specifically v2.47.1, I encountered a situation where

driver.findElements(By.className("someClass"))
was not sufficient for my needs. In this case, I found that using
driver.findElements(By.xpath("/path/to/[@class='someClass']"))
did the trick. This method returns a List<WebElement>. It's worth noting that By.xpath could be slower than other options on certain browsers, although the difference is typically minimal...

Answer №3

To start, the first step is to retrieve the elements collection:

public async fetchAppsList(): Promise<any[]> {
   const appsCollection: WebComponent = this.browser.find(By.css(`div .icons__title`));
   return await appsCollection.getElements();
}

Next, utilizing the function above allows you to perform various tasks, such as extracting and storing the text property. For instance, if it pertains to a group of Apps buttons and you wish to extract an array of their names:

public async getAppsNamesList(): Promise<string[]> {
const appsList: string[] = [];
let appName: string = '';

(await this.fetchAppsList()).forEach(async element => {
  await Promise.resolve(element).then(async (textItem: any) => {
    appName = await (await textItem.getText());
    appsList.push(appName);
  });
});

return appsList;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Selenium will only extract the initial item it comes across

Whenever I want to extract information from a website, I rely on this code block: driver = webdriver.Chrome(executable_path=r'C:/Users/USER/Downloads/chromedriver_win32/chromedriver.exe') url = 'https://mamikos.com/cari/ugm/all/bulanan/0-150 ...

What potential issues can arise when importing a default export alongside a named export and using webpack in conjunction with babel?

I have two distinct constructors in my codebase: SignUp and GoogleSignIn. They are structured as follows: import SignUp, {gapi_promise} from "./SignUp"; /** * * @param element * @extends SignUp * @constructor */ function GoogleSignIn(element){ SignUp ...

When the user selects either option 1 or 2 and presses the enter button, the model will dynamically update to reflect their chosen input

Using a script to retrieve the input value from an input box, there are two different models named model1s and model2s. The user must enter either 1 or 2 to determine which model pops up when the Enter button is clicked. <script> function displa ...

What is the best way to organize the password reset process for Firebase authentication?

Exploring the possibilities with the Firebase authentication solution for user registration and login in my Ionic application has led me to a hurdle in implementing the 'password reset flow'. When a user forgets their password, the current flow ...

Exploring the ID search feature in JavaScript

I'm facing an issue with implementing a search feature in my project. Here is the HTML snippet: HTML: <input type="text" id="search"> <video src="smth.mp4" id="firstvid"> <video src="smth2.m ...

Using nested components in Angular 2: A guide

I recently delved into Angular 2 and encountered an issue while working with components. I am attempting to integrate the "NavigationComponent" component within the template of my "MyApp" component. Here is the code for the "MyApp" component (/app/app.com ...

Combining two objects: A guide for merging with AngularJS or basic JavaScript

There are two sets of data $scope.c= {"Sedan":{"Toyota":["Camry","Corolla"]},"SUV":{"Jeep":["Wrangler"]}}; var d= {"SUV":{"Ford":["Escape"],"Chevrolet":["Tahoe"]}}; After combining the two sets, I expect to see the following outcome {"Sedan":{"Toyota": ...

Initiate CSS-Transitions using JavaScript

Despite reading 5 tutorials on how to initiate a CSS-Transition with JavaScript, I am unable to get it to work properly. My current browser is Safari. Below is the code that I have been working on: <html> <head> <title>Test</title&g ...

Navigating through nested JSON objects using JavaScript

Trying to access and display a nested JSON object within the console. This is the JSON data: { "currentUser": { "image": { "png": "./images/avatars/image-juliusomo.png", "webp": "./images/avatars/image-juliusomo.webp" }, "us ...

Building Xpath in Selenium WebDriver

I'm working with an Element Xpath //img[@onclick="EditResource(this,'10','0');"] My goal is to utilize this in a loop by replacing 10 with a variable i. driver.findElement(By.xpath("//img[@onclick='EditResource(this,' ...

AngularJS does not bind redefined variables

Having just started delving into Angular, I've encountered an issue while creating an application where a single AngularJS bind fails to update when the value of the bound object changes. This is a simplified version of the app, hence its structure. ...

Having trouble uploading images from my personal computer onto Phaser 3

Currently in the process of coding a game for a school project using Phaser. I am quite new to Phaser and have very little knowledge of JavaScript. Despite searching online for potential solutions, none seem to be effective for me. I have included my cod ...

Having difficulty inputting a value into a text box with Selenium

Looking for a way to automate updating my contact number on Naukri.com. I was successful in fetching the value from the text box, but encountered issues when trying to update it. Here's what I attempted: WebElement phoneNumber = driver.findElement(By ...

Exploring XML with Jquery

Looking for assistance with parsing my XML Feed: Struggling to utilize JQuery to extract and display the data in HTML. Despite searching on Google, I haven't found a satisfactory solution yet. With numerous elements in my XML, it's proving to b ...

Determine value by correlating the JSON key and value with another JSON file using JavaScript/Node.js

Attempting to set a json value by comparing deeply nested json objects The initial json object result appears as follows when logged: result { "computer": { "en": { "4gSSbjCFEorYXqrgDIP2FA": { "galle ...

The PHP script encountered an issue when trying to pass a MySQL request through to the getJSON() function

Seeking guidance from an expert on the following enigma. In my HTML, I utilized getJSON(). When using a hardcoded array that can be json_encoded (by setting $DEBUG = true), the data is passed to JavaScript for browser display successfully. However, encou ...

Load an external script once the page has finished loading by leveraging the power of $(document).ready() in conjunction with $.getScript()

Is it possible to load a script in the header of a website instead of at the bottom? I've been trying but it's not working as expected. Here is an example of what I'm attempting: HTML file: <!DOCTYPE html> <html lang="en"> < ...

"What is the best method to transfer a JsonObject from an Android Activity to JavaScript

Can someone please explain how I can send a JsonObject from my Android Activity to a Webview? Specifically, I want to pass the object to a JavaScript page. Any guidance on this matter would be greatly appreciated. ...

Retrieve the most recently added element of a particular class from the DOM using XPath

My website has a feature that generates multiple popups (don't judge my revenue strategy). Each popup is a complex div element that I need to access via xpath, preferably the last one added to the DOM as it will be the topmost. I attempted this appro ...

Customizing variables in React based on the environment

I am working on a React app that includes a chart component which calls an external API. When the app is running locally, the API URL is set to localhost:8080. However, when the app is deployed, the API URL needs to be changed to prod:8080. I have tried ...