How to Find and Manipulate Elements in JavaScript?

Learn how to find and manipulate elements in JavaScript for dynamic web functionality. Use BrowserStack Automate to test across real devices.

Get Started free
How to Find and Manipulate Elements in JavaScript
Home Guide How to Find and Manipulate Elements in JavaScript?

How to Find and Manipulate Elements in JavaScript?

JavaScript powers interactivity on modern websites, enabling dynamic content updates, animations, and real-time user interactions. Finding and manipulating elements on a webpage is crucial for enhancing the user experience.

This process relies on the Document Object Model (DOM), a hierarchical structure representing a webpage’s HTML. With JavaScript, developers can access, modify, or remove elements, change attributes, and respond to events.

This guide covers essential methods for selecting DOM elements and techniques for modifying text, styles, and attributes to create dynamic web applications.

What are JavaScript HTML DOM Elements?

JavaScript HTML DOM elements are the building blocks of a webpage that JavaScript can interact with through the Document Object Model (DOM).

The DOM is a programming interface that represents the structure of a webpage as a tree-like hierarchy of objects. Each object in this hierarchy corresponds to an HTML element in the webpage, such as a <div>, <p>, <img>, or <button>.

These DOM elements allow developers to programmatically access, modify, and manipulate the content and appearance of a webpage using JavaScript. With the DOM, you can dynamically update text, change styles, respond to user interactions, or even create and delete elements on the fly.

For example, if your HTML includes the following:

<div id="example">Hello, world!</div>
Copied

Using JavaScript, you can target and modify this element:

// Select the element by its ID

const element = document.getElementById("example");



// Change its content

element.textContent = "Hello, JavaScript!";
Copied

The ability to work with DOM elements effectively is a fundamental skill in JavaScript, enabling developers to create dynamic and interactive web applications.

Importance of Accessing HTML DOM Elements

Accessing HTML DOM (Document Object Model) elements is fundamental to web development, enabling developers to create dynamic, interactive, and responsive web applications.

Here are some key reasons why accessing HTML DOM elements is important:

  • Real-Time Changes: By accessing DOM elements, developers can dynamically update content on a webpage without requiring a full page reload. This is essential for smooth user experiences like live updates, notifications, or chat applications.
  • Interactive Features: DOM manipulation allows for interactive features like showing/hiding elements, updating text, or modifying styles based on user actions.
  • Event Handling: Accessing DOM elements allows developers to attach event listeners (e.g., click, mouseover, keypress) to respond to user interactions. This is crucial for creating responsive and engaging interfaces.
  • Form Validation: DOM access enables real-time validation of user inputs in forms, improving usability and reducing errors.
  • Dynamic Styling: Developers can modify CSS properties of DOM elements (e.g., style, classList) to create animations, transitions, or adaptive designs.
  • Responsive Design: Accessing DOM elements allows for adjusting layouts and styles based on screen size, device orientation, or other conditions.
  • Data-Driven Applications: DOM access is essential for binding data to the UI in frameworks like React, Angular, or Vue.js. This ensures that the UI reflects the current state of the application.
  • Content Manipulation: Developers can insert, remove, or modify elements to reflect data or application state changes.
  • Accessibility Improvements: Accessing DOM elements allows developers to enhance accessibility by dynamically updating ARIA attributes, focus management, and screen reader content.
  • SEO Optimization: Manipulating the DOM can help improve search engine visibility by dynamically generating or updating meta tags, headings, and structured data.

How to Find Elements in JavaScript

Finding HTML elements is the first step in interacting with the Document Object Model (DOM) in JavaScript. The process involves selecting elements using specific methods, depending on attributes like id, class, tag name, or CSS selectors.

Once elements are selected, they can be manipulated to update content, styles, or behaviors.

Here’s an overview of common methods to find HTML elements, followed by examples.

1. Finding HTML Elements by ID

Below is an example and explanation of finding HTML elements by ID:

Syntax:

document.getElementById("id");
Copied

Example:

html



<div id="greeting">Hello, World!</div>

<script>

  const element = document.getElementById("greeting");

  console.log(element.textContent); // Output: "Hello, World!"

</script>
Copied

Explanation:

  • Parameters: id is a string representing the id attribute of the target element.
  • This method returns the first matching element with the given ID. It is fast and reliable since IDs should be unique in HTML.

2. Finding HTML Elements by Tag Name

Below is an example and explanation of finding elements by tag name:

Syntax:

document.getElementsByTagName("tagName");
Copied

Example:

<ul>

  <li>Item 1</li>

  <li>Item 2</li>

</ul>

<script>

  const items = document.getElementsByTagName("li");

  console.log(items.length); // Output: 2

  console.log(items[0].textContent); // Output: "Item 1"

</script>
Copied

Explanation:

  • Parameters: tagName is the tag name (e.g., div, p, li) you want to select.
  • Returns an HTMLCollection of all elements with the given tag name. You can access elements using array-like indexing, but it’s not a true array.

3. Finding HTML Elements by Class Name

Below is an example and explanation of finding elements by class name.

Syntax:

document.getElementsByClassName("className");
Copied

Example:

<div class="box">Box 1</div>

<div class="box">Box 2</div>

<script>

  const elements = document.getElementsByClassName("box");

  console.log(elements.length); // Output: 2

  console.log(elements[0].textContent); // Output: "Box 1"

</script>
Copied

Explanation:

  • Parameters: className is a string representing the class attribute of the elements you want to select.
  • Returns an HTMLCollection of all elements with the specified class.

4. Finding HTML Elements by CSS Selectors

Below is an example and explanation of finding elements by CSS selectors:

Syntax:

document.querySelector("selector"); // Single element

document.querySelectorAll("selector"); // All matching elements
Copied

Example:

<div class="box" id="unique-box">Box 1</div>

<div class="box">Box 2</div>

<script>

  const singleBox = document.querySelector("#unique-box");

  console.log(singleBox.textContent); // Output: "Box 1"



  const allBoxes = document.querySelectorAll(".box");

  console.log(allBoxes.length); // Output: 2

</script>
Copied

Explanation:

  • Parameters: selector is a CSS selector (e.g., .class, #id, tagName).
  • querySelector returns the first matching element, while querySelectorAll returns a NodeList of all matching elements, which is iterable.

5. Finding HTML Elements by HTML Object Collections

Below is an example and explanation of finding elements by HTML object collections:

Syntax:

document.forms;          // Accesses all <form> elements

document.images;         // Accesses all <img> elements

document.links;          // Accesses all <a> elements

document.scripts;        // Accesses all <script> elements

document.anchors;        // Accesses all <a> elements with a name attribute
Copied

Example:

<form id="myForm">

  <input type="text" />

</form>

<img src="image.jpg" alt="Example" />

<a href="#section">Go to Section</a>

<script>

  console.log(document.forms[0].id); // Output: "myForm"

  console.log(document.images[0].src); // Output: "image.jpg"

  console.log(document.links[0].href); // Output: URL of the link

</script>
Copied

Explanation:

  • These are predefined HTMLCollections for specific types of elements on the page.
  • Useful for quick access to common groups of elements like forms, images, or links.

How to Use Selenium With JavaScript to Find Elements?

Selenium is a powerful tool for automating web applications, commonly used for testing. With Selenium in JavaScript, you can control browsers and interact with webpage elements through the WebDriver API, enabling efficient element location and manipulation.

Here’s a step-by-step guide and an example to help you understand how to use Selenium with JavaScript to find elements.

1. Prerequisites

Before using Selenium with JavaScript, ensure you have the following installed:

  • Node.js: JavaScript runtime for executing Selenium scripts.
  • Selenium WebDriver: Install it using npm:
npm install selenium-webdriver
Copied
  • Browser Driver: Download a browser-specific WebDriver (e.g., ChromeDriver for Chrome)

2. Finding Elements in Selenium

Selenium provides various methods to locate elements:

  • By ID: findElement(By.id(“id”))
  • By Class Name: findElement(By.className(“className”))
  • By Tag Name: findElement(By.tagName(“tagName”))
  • By CSS Selector: findElement(By.css(“selector”))
  • By XPath: findElement(By.xpath(“xpath”))

3. Example Code

Below is an example of using Selenium with JavaScript to open a webpage, find elements, and interact with it.

Example: Searching for a Term on Google

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



(async function example() {

  // Step 1: Initialize WebDriver

  let driver = await new Builder().forBrowser("chrome").build();



  try {

    // Step 2: Open Google

    await driver.get("https://www.google.com");



    // Step 3: Locate the Search Box (By Name)

    let searchBox = await driver.findElement(By.name("q"));



    // Step 4: Input Search Term

    await searchBox.sendKeys("Selenium WebDriver", Key.RETURN);



    // Step 5: Wait for Results to Load (By CSS Selector)

    await driver.wait(

      until.elementLocated(By.css("h3")), // Wait for search result titles

      10000 // Timeout after 10 seconds

    );



    // Step 6: Fetch the First Search Result Title

    let firstResult = await driver.findElement(By.css("h3"));

    console.log("First Search Result: ", await firstResult.getText());

  } catch (err) {

    console.error("An error occurred: ", err);

  } finally {

    // Step 7: Close the Browser

    await driver.quit();

  }

})();
Copied

Explanation of the Code

  1. Initialization: A WebDriver instance is created using Builder and configured to use Chrome.
  2. Navigating to a URL: The driver.get() method navigates to the specified URL (https://www.google.com).
  3. Locating Elements: The search box is located using By.name(“q”), which targets the name attribute of the input field.
  4. Interacting with Elements: The sendKeys() method inputs text into the search box and simulates pressing the Enter key.
  5. Waiting for Elements: The driver.wait() method waits until the first result (an <h3> element) is loaded.
  6. Fetching Text: The getText() method retrieves the text content of the first search result.
  7. Closing the Browser: The driver.quit() method closes the browser to clean up resources.

Methods to Manipulate Elements in JavaScript

Manipulating elements in JavaScript is essential for building dynamic and interactive web applications. Once you have accessed HTML elements through the DOM, you can use various methods to change their content, attributes, styles, and structure.

Here are the most commonly used methods for manipulating elements in JavaScript:

1. Modifying Content

textContent: Updates the plain text inside an element.

Example

document.getElementById("example").textContent = "Updated text content!";
Copied

innerHTML: Updates or retrieves the HTML structure inside an element.

Example

document.getElementById("example").innerHTML = "<b>Bold text!</b>";
Copied

innerText: Similar to textContent but considers the CSS styling (like visibility or display).

2. Modifying Attributes

setAttribute: Adds or updates an attribute.

Example

document.querySelector("img").setAttribute("src", "new-image.jpg");
Copied

getAttribute: Retrieves the value of an attribute.

Example

const altText = document.querySelector("img").getAttribute("alt");

console.log(altText);
Copied

removeAttribute: Removes an attribute.

Example

document.querySelector("input").removeAttribute("disabled");
Copied

3. Manipulating Styles

Inline Styles: Modify CSS directly using the style property.

Example

document.getElementById("box").style.backgroundColor = "blue";
Copied

classList

Manage classes using methods like:

  • add: Adds a class.
  • remove: Removes a class.
  • toggle: Adds or removes a class based on its presence.
  • contains: Checks if an element has a specific class.

Example

const element = document.querySelector(".box");

element.classList.add("highlight");

element.classList.toggle("active");
Copied

4. Creating and Removing Elements

createElement: Creates a new element.

Example

const newDiv = document.createElement("div");

newDiv.textContent = "I am a new div!";

document.body.appendChild(newDiv);
Copied

appendChild: Adds an element as a child of a parent.

Example

const parent = document.getElementById("container");

const child = document.createElement("p");

child.textContent = "New Paragraph";

parent.appendChild(child);
Copied

remove: Removes an element from the DOM.

Example

document.querySelector("#example").remove();
Copied

replaceChild: Replaces an existing child element with a new one.

Example

const parent = document.getElementById("container");

const newChild = document.createElement("h2");

newChild.textContent = "Replaced Heading";

const oldChild = document.querySelector("h1");

parent.replaceChild(newChild, oldChild);
Copied

Best Practices for Finding and Manipulating Elements in JavaScript

When working with the DOM to find and manipulate elements in JavaScript, following best practices ensures code readability, maintainability, and performance. Here’s a guide to help you work effectively:

1. Use Modern DOM Methods

Modern methods like querySelector and querySelectorAll are versatile, easier to use, and more consistent than older methods.

Best Practice:

  • Prefer document.querySelector() for finding single elements.
  • Use document.querySelectorAll() to find multiple elements.

Example

const button = document.querySelector(".btn");

const items = document.querySelectorAll(".item");
Copied

2. Be Specific with Selectors

Avoid ambiguous selectors to ensure you target the correct elements and reduce the risk of selecting unintended ones.

Best Practice:

  • Use unique ids when possible for precision.
  • Use class names or a combination of CSS selectors for complex queries.

Example

// Good

const submitButton = document.querySelector("#form .btn-submit");



// Avoid generic selectors like this

const button = document.querySelector("button");
Copied

3. Minimize DOM Traversals

Repeatedly querying the DOM can be costly in terms of performance.

Best Practice:

  • Store references to elements in variables if you need to use them multiple times.

Example

// Bad: Multiple DOM queries

document.querySelector(".container").classList.add("active");

document.querySelector(".container").style.color = "red";



// Good: Single query, stored reference

const container = document.querySelector(".container");

container.classList.add("active");

container.style.color = "red";
Copied

4. Use classList for Class Manipulation

The classList API is cleaner, more efficient, and less error-prone than directly manipulating the className property.

Best Practice:

  • Use classList.add, classList.remove, classList.toggle, and classList.contains.

Example

const box = document.querySelector(".box");



// Add a class

box.classList.add("highlight");



// Remove a class

box.classList.remove("inactive");



// Toggle a class

box.classList.toggle("visible");
Copied

5. Avoid innerHTML When Possible

Using innerHTML can introduce security risks (e.g., Cross-Site Scripting attacks) if the input is not sanitized.

Best Practice:

  • Use textContent for plain text.
  • Use createElement and appendChild for adding structured HTML safely.

Example

// Unsafe

element.innerHTML = "<script>alert('Hacked!');</script>";



// Safer Alternatives

element.textContent = "Hello, World!";

const newDiv = document.createElement("div");

newDiv.textContent = "Safe content";

element.appendChild(newDiv);
Copied

BrowserStack Live Banner

Test JavaScript on Real Devices with BrowserStack

BrowserStack is a cloud-based platform for testing JavaScript on real devices and browsers. It enables interactive Live Testing and Automated Testing with popular frameworks like Selenium.

The platform offers various devices and browsers, ensuring your code works seamlessly across different environments.

Key Benefits of Using BrowserStack for JavaScript Testing:

  • Real Device Testing: Test on various real devices and browsers for accurate results.
  • Live Testing: Interact with your web app in real time to test JavaScript functionality.
  • Automated Testing: Run tests using popular frameworks like Selenium, Cypress, and Playwright.
  • Cross-Browser Compatibility: Ensure seamless performance across multiple browsers and devices.
  • Built-in Debugging Tools: Inspect elements, debug JavaScript errors, and monitor console output directly.
  • Comprehensive Device Coverage: Test on various OS versions, screen sizes, and configurations.
  • No Setup Required: No need to maintain devices or worry about complex testing infrastructure.

BrowserStack Automate Banner

Below are the steps to test JavaScript with Automated Testing:

1. Install the necessary libraries for BrowserStack, such as browserstack-local and selenium-webdriver:

npm install browserstack-local selenium-webdriver
Copied

2. Obtain your Username and Access Key from the BrowserStack dashboard.

3. Use JavaScript with Selenium to write a test case for your application.

Example:

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



const USERNAME = "your_browserstack_username";

const ACCESS_KEY = "your_browserstack_access_key";



const capabilities = {

  browserName: "Chrome",

  browserVersion: "latest",

  os: "Windows",

  osVersion: "10",

  "browserstack.user": USERNAME,

  "browserstack.key": ACCESS_KEY,

};



(async function testJSOnBrowserStack() {

  let driver = await new Builder()

    .usingServer("https://hub-cloud.browserstack.com/wd/hub")

    .withCapabilities(capabilities)

    .build();



  try {

    await driver.get("https://example.com");

    const element = await driver.findElement(By.css("h1"));

    console.log("Page Header:", await element.getText());

  } catch (error) {

    console.error("Error:", error);

  } finally {

    await driver.quit();

  }

})();
Copied
  • Execute the script, and it will run on the selected BrowserStack device.
  • Use BrowserStack Local to test JavaScript on your local development server. Download and install the BrowserStack Local binary to establish a secure connection.
./BrowserStackLocal --key YOUR_ACCESS_KEY
Copied

Once connected, you can test your local web applications on real devices via BrowserStack.

Talk to an Expert

Conclusion

Understanding JavaScript DOM manipulation is essential for building dynamic web applications. Developers can efficiently interact with web page elements by using methods like getElementById, querySelector, and getElementsByClassName, enhancing user experience and functionality.

Using tools like BrowserStack for testing and adhering to best practices ensures smoother development. These skills provide a solid foundation for creating responsive and interactive web applications and can help developers advance to more complex JavaScript frameworks.

Tags
Automation Testing Manual Testing Real Device Cloud