Hero Background

Next-Gen App & Browser Testing Cloud

Trusted by 2 Mn+ QAs & Devs to accelerate their release cycles

Next-Gen App & Browser Testing Cloud
Testing

Selenium JavaScript Tutorial: Examples and Best Practices

Learn Selenium with JavaScript step by step: set up Node.js, write your first test, master locators and waits, and run cross-browser tests on the cloud.

Author

Saniya Gazala

Author

Author

Navin Chandra

Reviewer

June 23, 2026

Modern web applications rely on frequent releases, making automated browser testing essential for catching regressions before they reach users. Selenium JavaScript combines the industry's most established browser automation framework with the language that powers most modern web applications, allowing you to build and maintain tests without leaving the JavaScript ecosystem.

If you build web applications in JavaScript, you can automate them in JavaScript too. Selenium JavaScript helps validate user journeys, UI interactions, forms, and cross-browser behavior while reducing the context switching that comes with using a different programming language for automation.

From setting up Node.js and writing your first test to working with locators, waits, JavaScriptExecutor, and cross-browser execution, every example below is designed to help you build reliable and maintainable browser automation.

Overview

Why pair JavaScript with Selenium for automation?

Because your team can test in the same language it already builds with. JavaScript leads web development, so reusing it for automation keeps reviewers in a single mental model, opens up the npm ecosystem of runners and reporters, and aligns naturally with the asynchronous way browsers behave.

Are Selenium and JavaScript competing choices?

No, they operate at different levels and complement one another. JavaScript is the language you express your logic in, while Selenium is the framework that drives the browser and ships bindings for several languages. Combining them simply means steering Selenium WebDriver through its JavaScript binding.

How can you run Selenium JavaScript tests on many browsers at once?

TestMu AI (formerly LambdaTest) lets you run Selenium JavaScript tests across real browsers, devices, and operating systems in parallel without managing infrastructure yourself.

  • Scalable Selenium JavaScript execution: Run the same test suite across thousands of real browser and OS combinations without maintaining local grids.
  • Faster automation testing cycles: Execute tests in parallel to reduce feedback time and accelerate release validation.
  • Smarter test maintenance: With auto-healing, the platform automatically detects and repairs broken locators caused by UI changes, helping teams reduce maintenance effort and flaky tests.
  • Real browser and device coverage: Validate user experiences on real browsers, real devices, and real-world environments instead of emulators.
  • AI-powered quality workflows: TestMu AI (formerly LambdaTest) combines cloud Selenium execution with AI agents that help teams plan, author, execute, and analyze software quality at scale.

Why Use JavaScript for Selenium Automation?

You use JavaScript for Selenium so your team can automate in the same language it builds the app in, reusing one toolchain, the npm ecosystem, and native async handling.

JavaScript is the default language of the web, so writing your Selenium tests in it removes friction for the people most likely to own those tests: the developers who already wrote the app. In the Stack Overflow 2025 Developer Survey, JavaScript was again the most-used programming language, reported by 66% of all respondents. That reach is exactly why a JavaScript test stack is easy to staff and easy to review.

Choosing JavaScript for Selenium automation testing gives you concrete advantages:

  • One language across the stack: Your app, your unit tests, and your end-to-end Selenium tests all live in JavaScript, so reviewers do not switch mental models.
  • A huge ecosystem: npm gives you ready-made test runners, assertion libraries, and reporters that drop straight into a Selenium project.
  • Native async handling: Modern Selenium JavaScript uses async/await, which maps cleanly onto how the browser and network actually behave.
  • A strong fit for JS frameworks: Apps built in React, Angular, or Vue are a natural match for tests written in the same language.

Selenium is one well-supported route into JavaScript automation testing, sitting alongside runner-driven options that you can compare with other popular JavaScript testing frameworks before selecting the right stack for your project.

Selenium vs JavaScript: Clearing Up the Confusion

A lot of people search for "selenium vs javascript" as if you have to pick one. You do not. They sit at different layers, and you use them together.

AspectJavaScriptSelenium
What it isA programming language used to write application and automation codeA browser automation framework that drives web browsers
Primary purposeBuilding web applications, APIs, servers, and scriptsAutomating browser actions and testing web applications
Role in automationDefines the test logic, assertions, loops, conditions, and data handlingExecutes browser interactions such as clicks, typing, navigation, and element lookup
Runs where?Browser, Node.js, and server environmentsControls real browsers through WebDriver
Can it automate browsers alone?Limited browser automation through browser APIs, but not cross-browser testing at scaleDesigned specifically for browser automation across Chrome, Firefox, Edge, Safari, and more
Language supportJavaScript onlySupports JavaScript, Java, Python, C#, Ruby, and other languages
Learning focusSyntax, asynchronous programming, modules, and application developmentLocators, waits, WebDriver commands, browser sessions, and test design patterns
Example responsibilityif, for, async/await, API calls, data processingclick(), sendKeys(), findElement(), browser navigation
Dependency relationshipCan be used without SeleniumRequires a programming language such as JavaScript to define automation logic
Used together?Yes. JavaScript provides the test code.Selenium executes the browser automation described by that code.

"Selenium JavaScript" simply means you are calling Selenium WebDriver through its official JavaScript binding, the selenium-webdriver npm package.

The same framework also has bindings for Java, Python, C#, and Ruby, so the WebDriver concepts you learn here can be applied across different languages.

If you want to deepen your understanding, follow Selenium testing tutorial to explore more advanced automation patterns and best practices. The only real decision is which language your team is fastest in, and for web teams, that answer is usually JavaScript.

How to Set Up Selenium With JavaScript

Selenium JavaScript runs on Node.js, so your setup is short. You need three things: the Node.js runtime, the selenium-webdriver package, and a browser driver.

Step 1: Install Node.js: Download the latest LTS build from the official Node.js site. It bundles npm, the package manager you will use to pull in Selenium. Confirm both are available:

node -v
npm -v

Step 2: Create a project and install Selenium: The current release of the JavaScript binding is selenium-webdriver 4.44.0, which follows the W3C WebDriver standard.

mkdir selenium-js-demo && cd selenium-js-demo
npm init -y
npm install selenium-webdriver

Step 3: Get a browser driver: Selenium 4 ships with Selenium Manager, which downloads the matching driver (ChromeDriver, GeckoDriver, and so on) automatically the first time you run a test, so for local Chrome or Firefox you usually do not install anything else. With setup done, you are ready to write a test.

With the setup complete, you can start writing and running tests immediately. If you're familiar with older Selenium releases, Selenium 4 includes several important changes beyond driver management that can affect how existing test suites behave.

Everything here runs on Selenium 4, which replaced the legacy JSON Wire protocol with the native W3C WebDriver standard and introduced relative locators and a redesigned Grid. Follow this detailed Selenium 4 tutorial to explore these features in depth and understand how they can affect existing test suites during an upgrade.

How to Write Your First Selenium JavaScript Test

To write your first Selenium JavaScript test, build a driver, open the page, find an element, perform an action like typing or clicking, check the result, then close the browser session.

This first test opens the Selenium Playground, submits a message through the Simple Form Demo, and checks that the page echoes it back. Save it as firstTest.js:

const { Builder, By, until } = require("selenium-webdriver");

(async function firstTest() {
  const driver = await new Builder().forBrowser("chrome").build();
  try {
    await driver.get("https://www.testmuai.com/selenium-playground/");
    await driver.findElement(By.linkText("Simple Form Demo")).click();

    const message = "Welcome to TestMu AI";
    await driver.findElement(By.id("user-message")).sendKeys(message);
    await driver.findElement(By.id("showInput")).click();

    const output = await driver
      .wait(until.elementLocated(By.id("message")), 5000)
      .getText();
    console.log("Displayed message:", output);
  } finally {
    await driver.quit();
  }
})();

Run it with node firstTest.js. A Chrome window opens, fills the form, and prints the echoed message to your terminal. A few things are worth noticing: every WebDriver call returns a promise, so you await it; until.elementLocated waits for the result element instead of guessing with a fixed sleep; and the finally block guarantees the browser closes even if an assertion fails.

Want the same example explained step by step on video?

Once this script passes locally, you'll typically move it into a test runner. Test runners provide structure for organizing tests, executing suites, generating reports, and managing assertions as your automation project grows. Mocha is a popular lightweight choice for Selenium test suites, while Jest provides built-in assertions, mocking, and a more opinionated testing experience for JavaScript projects.

Understanding the differences in a Jest vs Mocha comparison can help you choose the framework that best matches your testing workflow.

Note

Note: Skip the local driver setup entirely and run this exact script across 3,000+ browser and OS combinations and 10,000+ real devices on the TestMu AI cloud grid. Start free.

Core Building Blocks of Selenium JavaScript Tests

Almost every Selenium JavaScript test is built from three ideas: finding elements, waiting for them, and occasionally dropping into raw JavaScript when WebDriver alone cannot reach something.

Locators

A locator tells Selenium how to find an element, and the By class exposes eight Selenium locators to do it. The order you reach for them decides how stable your test is: prefer an id, fall back to a name or a stable CSS selector, and treat XPath as a last resort because it breaks the moment the DOM shifts.

await driver.findElement(By.id("user-message"));        // most stable
await driver.findElement(By.name("q"));
await driver.findElement(By.css("button.submit"));
await driver.findElement(By.linkText("Simple Form Demo"));
await driver.findElement(By.xpath("//button[text()='Get Checked Value']")); // last resort

Waits

Modern pages load asynchronously, so the element you want may not exist the instant the page opens, and hard-coded sleeps are the number one cause of flaky tests. The fix is to reach for implicit, explicit, and fluent waits, each of which pauses only until your condition is met and then continues immediately:

// Good: waits only as long as needed, up to 10 seconds
const message = await driver.findElement(By.id("message"));
await driver.wait(until.elementIsVisible(message), 10000);

// Avoid: blocks for a fixed time whether the element is ready or not
await driver.sleep(10000);

JavaScriptExecutor

Sometimes a normal WebDriver command will not do, for example scrolling to a lazy-loaded element or clicking something covered by an overlay. driver.executeScript() runs raw JavaScript inside the page:

// Scroll an element into view, then read a value straight from the DOM
const button = await driver.findElement(By.id("showInput"));
await driver.executeScript("arguments[0].scrollIntoView(true);", button);

const title = await driver.executeScript("return document.title;");
console.log("Page title:", title);

Reach for the JavaScriptExecutor interface sparingly, since running script directly bypasses the real-user interaction Selenium is meant to simulate, and reserve JavaScriptExecutor in Selenium for edge cases where native WebDriver commands are insufficient.

Running Selenium JavaScript Tests Across Browsers on the Cloud

Maintaining every browser and OS version on local machines does not scale. Cloud-based Selenium testing allows you to run the same test suite across multiple real browsers, operating systems, and devices in parallel without managing infrastructure yourself.

One such cloud platform is TestMu AI (formerly LambdaTest), a Full Stack Agentic AI Quality Engineering platform that helps teams test intelligently and ship faster. Beyond scalable Selenium testing, it provides end-to-end AI agents that help teams plan, author, execute, and analyze software quality across web, mobile, and enterprise applications.

By connecting your Selenium tests to the TestMu AI cloud, you can execute them across thousands of real browser and OS combinations, real devices, and custom real-world environments while benefiting from enterprise-grade scale, observability, and AI testing insights.

const { Builder } = require("selenium-webdriver");

const capabilities = {
  browserName: "Chrome",
  browserVersion: "latest",
  "LT:Options": {
    platformName: "Windows 11",
    build: "Selenium JavaScript Demo",
    name: "First cloud test",
    user: process.env.LT_USERNAME,
    accessKey: process.env.LT_ACCESS_KEY,
  },
};

(async function cloudTest() {
  const driver = new Builder()
    .usingServer("https://hub.lambdatest.com/wd/hub")
    .withCapabilities(capabilities)
    .build();
  try {
    await driver.get("https://www.testmuai.com/selenium-playground/");
    console.log("Page title:", await driver.getTitle());
  } finally {
    await driver.quit();
  }
})();

Set your LT_USERNAME and LT_ACCESS_KEY as environment variables, then update the browserName and platformName capabilities to run the same test across different browser and operating system combinations. This allows you to validate cross-browser behavior on Chrome, Firefox, Edge, and Safari while scaling execution through TestMu AI's cloud infrastructure.

To get started with Selenium JavaScript automation on TestMu AI, follow the support documentation on Selenium With JavaScript.

Run JavaScript Selenium Tests Using Agent Skills

Use AI coding assistants to generate and run JavaScript Selenium tests with the TestMu AI Agent Skill. The selenium-skill is part of TestMu AI agent-skills, a collection of structured packages that teach AI coding assistants how to write production-grade Selenium test automation and execute it on TestMu AI.

These Selenium Skills help standardize automation workflows, making it easier to apply Selenium with AI techniques for test creation, maintenance, and execution. As AI-assisted development becomes more common, they also support emerging vibe testing with Selenium workflows, where natural language prompts are used to generate and refine automated tests.

Install the skill:

git clone https://github.com/LambdaTest/agent-skills.git
cp -r agent-skills/selenium-skill .claude/skills/

# For Cursor / Copilot
cp -r agent-skills/selenium-skill .cursor/skills/

Once installed, your AI coding assistant can generate and run JavaScript Selenium tests using the TestMu AI Agent Skill, helping teams adopt Selenium AI workflows without changing their existing automation stack. For a complete setup and usage, follow the support documentation on running Selenium tests with Agent Skills.

Test across 3000+ browser and OS environments with TestMu AI

Selenium JavaScript Best Practices

A test suite that runs green today but breaks every sprint is worse than no suite at all. These Selenium best practices help keep your JavaScript tests fast, readable, and trustworthy as your automation suite grows.

  • Replace every sleep with an explicit wait: Fixed delays either waste time or fire too early. Proper use of Selenium waits helps synchronize tests with the application state and reduces flaky failures.
  • Use the Page Object Model: Keeping locators and page actions in dedicated page object classes means a UI change touches one file, not fifty tests. The Selenium Page Object Model(POM) helps improve maintainability by separating test logic from page-specific implementation details.
  • Prefer stable locators: Lean on IDs and data attributes over brittle XPath tied to page layout. Many teams use data attributes in JavaScript with Selenium to create selectors that remain stable across design and layout updates.
  • Keep tests independent: Each test should create its own preconditions and avoid relying on data or state left behind by other tests. Independent tests can run in any order, execute in parallel, and produce more reliable results.
  • Capture evidence on failure: A screenshot taken the moment a test fails turns a vague stack trace into an obvious visual clue and cuts debugging time. Capturing screenshots in Selenium WebDriver using JavaScript is a simple but effective way to speed up root cause analysis.
  • Test across real browsers early: A test that passes only in your local Chrome is not cross-browser coverage. Early cross-browser testing helps identify JavaScript browser compatibility issues that can behave differently across browser engines and versions.
Test your website on the TestMu AI real device cloud

Conclusion

Start small: install Node.js, run the firstTest.js script above against the Selenium Playground, and confirm it prints the echoed message. From there, wrap it in Mocha or Jest, move your locators into Page Objects, and swap fixed sleeps for explicit waits. Those few habits are what separate a suite you trust from one you fight.

When you're ready to test beyond your local machine, point your Selenium suite at the TestMu AI cloud grid and execute it across 3,000+ browser and OS combinations and 10,000+ real devices in parallel. Combined with AI test authoring, execution, and analysis, this allows teams to scale Selenium JavaScript automation without adding infrastructure or maintenance overhead.

Author

...

Saniya Gazala

Blogs: 42

  • Twitter
  • Linkedin

Saniya Gazala is a Product Marketing Manager and Community Evangelist at TestMu AI with 2+ years of experience in software QA, manual testing, and automation adoption. She holds a B.Tech in Computer Science Engineering. At TestMu AI, she leads content strategy, community growth, and test automation initiatives, having managed a 5-member team and contributed to certification programs using Selenium, Cypress, Playwright, Appium, and KaneAI. Saniya has authored 15+ articles on QA and holds certifications in Automation Testing, Six Sigma Yellow Belt, Microsoft Power BI, and multiple automation tools. She also crafted hands-on problem statements for Appium and Espresso. Her work blends detailed execution with a strategic focus on impact, learning, and long-term community value.

Reviewer

...

Navin Chandra

Reviewer

  • Linkedin

Navin Chandra is a Member of Technical Staff at TestMu AI (formerly LambdaTest), building the open-source automation that powers its Selenium and Appium cloud grid. A committer to both Selenium and Appium, he implemented WebDriver BiDi support in Selenium for real-time browser events and bidirectional control and is developing Apple's iOS RemoteXPC protocol in Appium to enable low-level wireless communication with iOS system services. He contributes to Selenium across multiple language bindings as a member of the Selenium GitHub organization. He has served as a Google Summer of Code mentee and mentor at openSUSE and an LFX mentee at CNCF's KubeArmor, and is a SUSE Certified Deployment Specialist. Navin holds a B.Tech in Computer Science.

Open in ChatGPT Icon

Open in ChatGPT

Open in Claude Icon

Open in Claude

Open in Perplexity Icon

Open in Perplexity

Open in Grok Icon

Open in Grok

Open in Gemini AI Icon

Open in Gemini AI

Copied to Clipboard!
...

3000+ Browsers. One Platform.

See exactly how your site performs everywhere.

Try it free
...

Write Tests in Plain English with KaneAI

Create, debug, and evolve tests using natural language.

Try for free

Selenium with JavaScript FAQs

Did you find this page helpful?

More Related Blogs

TestMu AI forEnterprise

Get access to solutions built on Enterprise
grade security, privacy, & compliance

  • Advanced access controls
  • Advanced data retention rules
  • Advanced Local Testing
  • Premium Support options
  • Early access to beta features
  • Private Slack Channel
  • Unlimited Manual Accessibility DevTools Tests