Continuous Test Orchestration And Execution Platform Online

Perform automated and live-interactive testing on 3000+ real desktop and mobile devices online.

How to Use JavaScript to Find Elements

Finding elements in the Document Object Model (DOM) involves inspecting the DOM structure using different methods. These methods help you find elements based on various criteria, including ID, Name, Class, Tag Name, etc. Locating the right element in the DOM is crucial to making any changes to the web page, such as changing the text of a button, hiding an image, or adding new content.

One way to do this is to use programming languages like JavaScript to find elements. On the other hand, finding elements is also crucial when testing websites as it allows test scripts to interact with the web page, verifying that elements behave as expected.

What is the Document Object Model?

The Document Object Model is a programming interface that structures a web page as a collection of nodes, such as HTML tags like <html>, <meta>, <title>, <body>, and others. This W3C standard represents web pages in a tree-like structure of nodes.

Document Object Model

The DOM allows web developers to manipulate, style, and structure these nodes (HTML documents). For example, JavaScript is used to dynamically change WebElements and add interactivity, while CSS enhances the aesthetics of the page.

Although JavaScript and CSS are primarily used on the front end due to their browser compatibility , the DOM can also be manipulated with other programming languages.

JavaScript Methods to Find Elements

JavaScript offers several methods to find and manipulate elements in the DOM. Here are some of the most common methods:

  • getElementById()
  • getElementsByName()
  • getElementsByClass()
  • getElementsByTagName()
  • querySelector()
  • querySelectorAll()

With these methods, you can access any DOM element by ID, Name, Class, Tag Name, etc. However, we have only two single methods: getElementById() and querySelector(), which return the WebElement, and the rest return a list of WebElements.

Note

Note : Run Your JavaScript Tests Across 3000+ Real Environments. Try LambdaTest Now!

How to Use JavaScript to Find Elements?

Now, let’s discuss how to use the above methods in JavaScript to find elements:

getElementById(): This method queries the document to get the element based on its ID attribute value. Below is the syntax for using this method to access elements in JavaScript.

document.getElementById(elementId);

Parameters:

  • elementId: The ID attribute value of an element.
  • Return value: If the element is found, it returns the element. If not, it returns null.

getElementsByName(): This method queries the document to get all the elements based on the name attribute value provided. Below is the syntax for using this method to access elements in JavaScript.

document.getElementsByName(elementName)

Parameters:

  • elementName: The Name attribute value of an element.
  • Return value: It returns all the elements found in a NodeList (Collection) of element(s). If not, it returns null.

getElementsByClass():This method queries the document to get all the elements based on the provided CSS class attribute value. Below is the syntax for using this method to access elements in JavaScript.

document.getElementsByClass(elementClass)

Parameters:

  • elementClass: The Class attribute value of an element.
  • Return value: It returns all the elements found in a NodeList (Collection) of element(s). If not, it returns null.

getElementsByTagName(): This method queries the document to get all the elements based on the provided tag name. Below is the syntax for using this method to access elements in JavaScript.

document.getElementsByTagName(tagName)

Parameters:

  • tagName: The tagName attribute of an element.
  • Return value: It returns all the elements found in a NodeList (Collection) of element(s). If not, it returns null.

querySelector(): This method is used to find an element using any selector. Below is the syntax for using this method to access elements in JavaScript.

document.querySelector(anySelector)

Parameters:

  • anySelector: Pass in any selector to select the element.
  • Return value: If the element is found, it returns the element. If not, it returns null.

querySelectorAll():This method finds all elements using the passed selector. Below is the syntax for using this method to access elements in JavaScript.

document.querySelectorAll(anySelector).

Here's an example of selecting input elements and printing them to the console using the querySelectorAll() method in JavaScript.

  const inputElements = document.querySelectorAll('form > input')
   for(const element of inputElements){
     console.log(element)
   }

Now, we know how to use JavaScript to find elements in the DOM. However, as mentioned earlier, finding elements is also crucial when performing automated cross browser testing to ensure that elements behave as expected.

Let’s use automation testing tools like Selenium with JavaScript to find elements. To find elements with JavaScript, Selenium provides findElement() and findElements() methods.

Selenium Methods to Find Elements

Let's explore the above methods and see how to use Selenium with JavaScript to find elements.

findElement()

It returns the first matching WebElement if the locator discovers multiple WebElements. It takes the By object from Selenium as a parameter to locate the element using different methods of the By object, such as ID, Name, ClassName, LinkText, XPath, etc.

Below is the syntax for the findElement() method in Selenium JavaScript :

const emailElement = driver.findElement(By.LocatorStrategy("LocatorValue"));

The LocatorStrategy is one of the following methods: ID, Name, ClassName, LinkText, XPath, etc., inside the By object, and the LocatorValue is the element's unique identifier.

Now, here is an example:

const emailElement = driver.findElement(By.id("email"));

findElements()

It is used to get the references to all the elements that match the locator. This method returns a collection of element references. If there are no matches, an empty list is returned. It takes the By object as the parameter and returns a list of WebElements. If none of the elements is found, it returns an empty list.

Below is the syntax and example of using the findElements() method in Selenium JavaScript to locate a list of elements:

const emailElements = driver.findElements(By.LocatorStrategy("LocatorValue"));

Now, here is an example:

const emailElements = driver.findElements(By.xpath("//input[type=email]"));

Now, let's explore some Selenium locators you can use with the findElement() and findElements() methods to locate and identify elements on your web page.

  • ID
  • Name
  • ClassName
  • TagName
  • Link Text
  • CSS
  • XPath

ID

The ID locator locates an element whose ID attribute matches the search value. We can use the ID of an element to locate it, and the ID attribute should be unique amongst other elements.

Let's look at an example of selecting the first name field using the id attribute in a form.

const firstname = await driver.findElement(By.id('fname'));

Name

The Name locator locates an element whose name matches the search value. We can use the name attribute of an element to locate it, which should be unique across all web page elements.

Below is a code snippet showing how to use the name property to locate an element. We will locate the last element using the name attribute.

const lastname = await driver.findElement(By.name('lastname'));

ClassName

The ClassName locator locates the element whose class name matches the search value. If your element has a ClassName, then we can locate that element using the className in Selenium JavaScript, as shown below:

// HTML
<div class="myDiv"></div>


// JS
const myDiv = driver.findElement(By.className('myDiv'));

TagName

The TagName locator locates an element whose TagName matches the search value. We can use the HTML tag as a locator to identify the WebElement on the page. Let's look at this example:

const anchor = await driver.findElement(By.tagName('a'));

LinkText

The LinkText locator locates an element whose visible text matches the search value. Assuming the element we want to locate is a link, we can use the LinkText to identify the element on the web page.

Below is an example of locating an element using the linkText locator.

const homePage = await driver.findElement(By.linkText('Home'));

CSS

The CSS locator locates an element matching a CSS Selector . We can use the CSS Selector locator strategy to identify the element on the page. If the element has an ID, we create the locator as css = #id. Otherwise, the format we follow is CSS =[attribute=value].

Let's look at examples of using the CSS locator to locate elements. Here, we will locate the name from a form.

const name = await driver.findElement(By.css('#name'));

XPath

The XPath locator locates an element matching the XPath expression. All HTML documents are also considered XML documents. Therefore, we can locate the XPath of any element. We can use the absolute path or relative path. The absolute path is created from the document's root, while the relative path uses predicates.

Let's look at some examples of using xpath to locate elements in Selenium JavaScript. Here, we will locate the username in a form.

// using relative pattern
const username = await driver.findElement(By.xpath('//input[@name='username']'));

// using absolute pattern
const username = await driver.findElement(By.xpath("/html/form/input[@name="userna

These are the locators used in Selenium with JavaScript to find elements. We didn't cover other locators, but these are the most popular. You can combine them with the findElement() or findElements() method to locate elements on your web page.

How to Use Selenium With JavaScript to Find Elements?

Let’s explore how to use Selenium with JavaScript to find elements. Here, the methods used are findElement() and findElements().

For demonstration, we will use the Form Demo page by LambdaTest Selenium Playground. This page has form inputs, text, buttons, and other WebElements.

by LambdaTest Selenium Playground

First, select the page title and display it on the console. We will achieve this using the findElement() method. Use the browser to inspect the page and get either the ID, Class, XPath, or HTML tag of the element we want to find, as shown below:

browser to inspect the page

Now, if you look closely at the H1 element, no unique CSS or ID attribute is assigned. Therefore, selecting this element with a Class or ID selector will be challenging. However, we can use XPath to select the element as shown below:

Chalet pageTitle = await driver
     .findElement(By.xpath("//*[@id="__next"]/div/section[1]/div/div/h1"))nge

To do that, right-click the element (H1) tag and click on Copy, then select Copy XPath or Copy full XPath.

With this method, you have selected a single element. Let's try out some examples with Class or ID selectors using the findElement() method.

Next, select the name input field following the same approach above. If you inspect the element, you will see it has an ID with the assigned name. Now, let's use that to find the element in Selenium.

let nameInput = await driver .findElement(By.id("name"))

We use the findElements() method to select a collection of elements. Let's look at an example of choosing all the input fields on a web page.

await driver.get("https://www.lambdatest.com/selenium-playground/input-form-demo");
 let inputElements = await driver.findElements(
   By.css("#seleniumform>input")
  );
  inputElements.forEach((element) => {
   console.log(element.getAttribute("value"));
  });

First, we visit the web page and select all the input elements using the findElements() method using the CSS Selector. Lastly, we printed out the values of each input.

Now, let’s look at other use cases of findElement() and findElements() methods, such as filling forms and retrieving a list of products while running Selenium tests. To achieve scalability and reliability, we will use a cloud-based grid like LambdaTest to run Selenium tests.

LambdaTest is an AI-powered test orchestration and execution platform that allows developers and testers to perform automation testing across different browsers and operating systems permutations.

With LambdaTest, testers can test websites in different browsers on cloud Selenium Grid without maintaining their own in-house test infrastructure.

...

Filling Forms Using findElement()

Let’s look at how to fill out a web form using the findElement() method. We will use the Form Demo page by LambdaTest Selenium Playground for demonstration. To get started, follow the below steps:

Install Selenium WebDriver

Install the Selenium WebDriver on your local machine using the below command:

npm install selenium-web driver

Add Environment Variables

Define your .env file and all the following:

LT_USERNAME=
LT_ACCESS_KEY=
GRID_HOST=

You can add the LambdaTest Username (LT_USERNAME) and, Access Key (LT_ACCESS_KEY), and grid host (GRID_HOST) from the Account Settings > Password & Security .

Configure the Test Script

Next, create a file in your directory and add the following code. This will be your entry file for the project.

const { Builder, By } = require("selenium-webdriver");
async function fillOutFormWithLambdaTest() {
 const LT_USERNAME = ""; //replace with your username
 const LT_ACCESS_KEY = ""; //replace with your accesskey
 const GRID_HOST = "hub.lambdatest.com/wd/hub";
 const capabilities = {
   browserName: "Chrome",
   browserVersion: "latest",
   "LT:Options": {
     username: LT_USERNAME,
     accessKey: LT_ACCESS_KEY,
     geoLocation: "US",
    platformName: "Windows 10",
     build: "Form Filling with LambdaTest",
     project: "Filling_Forms",
     w3c: true,
     plugin: "node_js-node_js",
   },
 };
 const gridUrl =
   "https://" + LT_USERNAME + ":" + LT_ACCESS_KEY + "@" + GRID_HOST;
 let driver;
 try {
   driver = await new Builder()
     .usingServer(gridUrl)
     .withCapabilities(capabilities)
     .build();
   return await fillOutFormWithSelenium(driver);
 } catch (error) {
   throw error;
 } finally {
   await driver.quit();
 }
}
LambdaTest

In the above test script, we defined automation capabilities using the LambdaTest Automation Capabilities Generator . Lastly, we created a driver using the GRID_HOST. Next, use the driver object to fill out web forms with Selenium.

Finding and Filling All Input Elements

Now, let's find and fill out all the input elements using the findElement() method in Selenium. Below is the test script for the same.

async function fillOutFormWithSelenium(driver) {
 //Launch the browser
 if (!driver) return;
 try {
   await driver.get(
     "https://www.lambdatest.com/selenium-playground/input-form-demo"
   );
   // Select all the input elements
   let nameElement = await driver.findElement(By.id("name"));
   let emailElement = await driver.findElement(By.name("email"));
   let passwordElement = await driver.findElement(By.id("inputPassword4"));
   let companyElement = await driver.findElement(By.id("company"));
   let websiteElement = await driver.findElement(By.name("website"));
   let countryElement = await driver.findElement(
     By.xpath(`//*[@id="seleniumform"]/div[3]/div[1]/select`)
   );
   let cityElement = await driver.findElement(By.css("input[placeholder='City'"));
   let address1Element = await driver.findElement(By.css("input#inputAddress1"));
   let address2Element = await driver.findElement(By.id("inputAddress2"));
   let stateElement = await driver.findElement(By.css("input#inputState"));
   let zipElement = await driver.findElement(By.id("inputZip"));
   // Select Submit button
   let button = await driver.findElement(
     By.xpath(`//*[@id="seleniumform"]/div[6]/button`)
   );
   // Set text to all the elements
   nameElement.sendKeys("Test Test");
   emailElement.sendKeys("test@test.com");
   passwordElement.sendKeys("password123");
   companyElement.sendKeys("Contentre");
   // Wait for a few seconds (optional) to observe the results
   await driver.sleep(1000);
   websiteElement.sendKeys("https://contentre.io");
   countryElement.sendKeys(Key.ARROW_DOWN, Key.ARROW_DOWN, Key.ENTER); // Select Aland Island
   cityElement.sendKeys("Port harcourt");
   address1Element.sendKeys("9 Prince Okey street");
   // Wait for a few seconds (optional) to observe the results
   await driver.sleep(1000);
   address2Element.sendKeys("Apartment 8");
   stateElement.sendKeys("Rivers");
   zipElement.sendKeys("200272");
   // Wait for a few seconds (optional) to observe the results
   await driver.sleep(1000);
   // Submit form
   button.click();
 } catch (error) {
   console.log(error);
 }
}

The above script receives the driver object from our setup and selects all the input elements. Let's get a walkthrough of each code section for better understanding.

Code Walkthrough:

Use the findElement() method to locate all the input fields on the page. Also, we used a combination of ID and XPath, respectively.

locate all the input fields on the page

Next, we set values to all the identified input elements using the Selenium sendKeys() method. You can also use different commands to select, input, and act on different form elements, as shown in the countryElement.

act on different form elements

Lastly, we submit the form using the Selenium click() button method.

submit the form using the Selenium click() button

Retrieving List of Products Using findElements()

Let’s look at how to retrieve a list of products using the findElements() method. We will use the LambdaTest eCommerce Playground for demonstration. To begin, follow the below steps:

Create the WebDriver

We will reuse the WebDriver code we created to perform this action and retrieve all the products from the LambdaTest eCommerce Playground.

Below is the test script that uses the findElements() method to retrieve all the products in a Node array.

static async resolve() {
   await this.init();
   const elements = await driver.findElements(
     By.css("div[data-view_id='grid']")
   );
   const products = [];
   for (const element of elements) {
     const productElement = await element.findElement(
       By.css("div > div > div> div.image > a")
     );
     const productURL = await productElement.getAttribute("href");
     const image = await productElement
       .findElement(By.css("div > div > img"))
       .getAttribute("src");
     const title = await productElement
       .findElement("div > div.caption > h4")
       .getText();
     const price = await productElement
       .findElement("div > div.caption > div.price > span")
       .getText();
     products.push({
       title,
       image,
       productURL,
       price,
     });
   }
   return products;
 }

Code Walkthrough:

Find the lists of elements that contain each product's details using the findElements() method and the CSS Selector, as shown below:

lists of elements that contain each product's

Loop through each product and collect the product details, such as product image, product name, and price, using the findElement() method and different selectors.

product and collect the product details

Push the product details into an array and return them as JSON responses:

array and return them as JSON

Conclusion

In conclusion, finding elements is essential for manipulating the Document Object Model (DOM) to create dynamic and interactive web pages. This can be accomplished using programming languages like JavaScript. Additionally, finding elements is crucial for testing websites, as it enables test scripts to interact with the web page and verify that elements function as expected.

Frequently Asked Questions (FAQs)

1. How to find element objects in JavaScript?

You can use document.getElementById('id'), document.querySelector('selector'), or document.getElementsByClassName('class')[index] to find an element.

2. How to check if the element is found in JavaScript?

To check if the element is null or undefined, you can use if (element) { ... } or if (element !== null) { ... }.

LambdaTest

Test your websites, web-apps, or mobile apps seamlessly with LambdaTest.

Start Free Testing
LambdaTest

Earn resume-worthy Selenium certifications that help you land a top job.

Learn More
LambdaTest

Test your web or mobile apps

Test orchestration and execution cloud of 3000+ browsers and OS

Support

24/7 support

Security

Enterprise grade security

Cloud

Fastest test execution cloud