How to Find and Manipulate Elements in JavaScript?

On This Page What are JavaScript HTML DOM Elements?April 29, 2026 · 15 min read · Testing Guide

How to Find and Manipulate Elements in JavaScript?

JavaScript powers interactivity on modern site, enabling active substance updates, animations, and real-time exploiter interaction.Finding and manipulating elementon a webpage is crucial for enhance the exploiter experience.

This procedure relies on the Document Object Model (DOM), a hierarchical structure representing a webpage & # 8217; s HTML. With JavaScript, developer can approach, alter, or remove elements, change attributes, and respond to events.

This usher 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 elementsare the building blocks of a webpage that JavaScript can interact with through the.

The DOMis a programming interface that represents the structure of a webpage as a tree-like hierarchy of objects. Each objective in this hierarchy equate to an HTML element in the webpage, such as a & lt; div & gt;, & lt; p & gt;, & lt; img & gt;, or & lt; button & gt;.

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

Also Read:

For example, if your HTML include the following:

& lt; div & gt; Hello, world! & lt; /div & gt;

Using JavaScript, you can target and modify this factor:

// Select the component by its ID const element = document.getElementById (`` example ''); // Change its content element.textContent = `` Hello, JavaScript! ``;

The power to act with DOM elements effectively is a fundamental skill in JavaScript, enabling developers to make dynamic and interactive web applications.

Importance of Accessing HTML DOM Elements

Accessing HTML DOM (Document Object Model) elements is underlying to, enable developers to make dynamic, interactive, and responsive.

Also Read:

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

  • Real-Time Changes: By accessing DOM component, developers can dynamically update message on a webpage without requiring a full page reload. This is all-important for smooth user experience like live updates, notifications, or schmoose applications.
  • Interactive Features: DOM use let for interactive features like showing/hiding ingredient, updating text, or alter styles based on user action.
  • Event Handling: Accessing DOM elements let developers to attach case listeners (e.g., click, mouseover, keypress) to respond to user interactions. This is crucial for creating responsive and engaging interface.
  • Form Validation: DOM access enables real-time substantiation of user stimulus in forms, improve usability and reducing errors.
  • Dynamic Styling: Developers can modify CSS properties of DOM elements (e.g., style, classList) to make animations, transitions, or adaptive designs.
  • Responsive Design: Accessing DOM elements allows for adapt layouts and manner establish on screen size, device orientation, or other conditions.
  • Data-Driven Applications: DOM access is essential for binding information to the UI in framework like React, Angular, or Vue.js. This see that the UI reflects the current state of the application.
  • Content Manipulation: Developers can enclose, remove, or modify elements to reflect data or application province modification.
  • Improvements: Accessing DOM elements allows developers to enhance accessibility by dynamically updating ARIA attributes, focus management, and screen reader substance.
  • SEO Optimization: Manipulating the DOM can help improve hunt engine profile by dynamically generating or update meta tags, headings, and structure data.

Also Read:

JavaScript Methods to Find Elements

Mentioned below are the most commonly used method in JavaScript to bump and misrepresent elements in the DOM:

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

These method let you approach any DOM constituent by ID, Name, Class, Tag Name, etc. Having allege that, only getElementById () and querySelector () return the WebElement, while the rest homecoming a list of WebElements.

How to Find Elements in JavaScript

Finding is the first step in interacting with the Document Object Model (DOM) in JavaScript. The procedure involves selecting constituent using specific method, depending on attributes like id, form, tag name, or CSS selectors.

Once element are selected, they can be manipulated to update content, style, or behaviors.

Also Read:

Here ’ s an overview of common method to find HTML constituent, followed by exemplar.

1. Finding HTML Elements by ID

Below is an example and explanation of:

Syntax:

document.getElementById (`` id '');

Example:

html & lt; div & gt; Hello, World! & lt; /div & gt; & lt; script & gt; const element = document.getElementById (`` recognize ''); console.log (element.textContent); // Output: `` Hello, World! '' & lt; /script & gt;

Explanation:

  • Parameters: id is a string representing the id dimension of the quarry element.
  • This method retrovert the 1st matching element with the given ID. It is fast and reliable since IDs should be unique in HTML.

Must Read:

2. Finding HTML Elements by Tag Name

Below is an representative and account of finding elements by tag gens:

Syntax:

document.getElementsByTagName (`` tagName '');

Example:

& lt; ul & gt; & lt; li & gt; Item 1 & lt; /li & gt; & lt; li & gt; Item 2 & lt; /li & gt; & lt; /ul & gt; & lt; book & gt; const items = document.getElementsByTagName (`` li ''); console.log (items.length); // Output: 2 console.log (items [0] .textContent); // Output: `` Item 1 '' & lt; /script & gt;

Explanation:

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

Also Read:

3. Finding HTML Elements by Class Name

Below is an example and explanation of gens.

Syntax:

document.getElementsByClassName (`` className '');

Example:

& lt; div & gt; Box 1 & lt; /div & gt; & lt; div & gt; Box 2 & lt; /div & gt; & lt; script & gt; const elements = document.getElementsByClassName (`` box ''); console.log (elements.length); // Output: 2 console.log (constituent [0] .textContent); // Output: `` Box 1 '' & lt; /script & gt;

Explanation:

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

Also Read:

4. Finding HTML Elements by CSS Selectors

Below is an example and explanation of finding factor by:

Syntax:

document.querySelector (`` selector ''); // Single element document.querySelectorAll (`` selector ''); // All matching elements

Example:

& lt; div & gt; Box 1 & lt; /div & gt; & lt; div & gt; Box 2 & lt; /div & gt; & lt; handwriting & gt; const singleBox = document.querySelector (`` # unique-box ''); console.log (singleBox.textContent); // Output: `` Box 1 '' const allBoxes = document.querySelectorAll (`` .box ''); console.log (allBoxes.length); // Output: 2 & lt; /script & gt;

Explanation:

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

Also Read:

5. Finding HTML Elements by HTML Object Collections

Below is an example and explanation of detect ingredient by HTML object collections:

Syntax:

document.forms; // Accesses all & lt; form & gt; element document.images; // Accesses all & lt; img & gt; constituent document.links; // Accesses all & lt; a & gt; elements document.scripts; // Accesses all & lt; book & gt; element document.anchors; // Accesses all & lt; a & gt; element with a name attribute

Example:

& lt; form & gt; & lt; input type= '' text '' / & gt; & lt; /form & gt; & lt; img src= '' image.jpg '' alt= '' Example '' / & gt; & lt; a href= '' # subdivision '' & gt; Go to Section & lt; /a & gt; & lt; script & gt; 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 & lt; /script & gt;

Explanation:

  • These are predefined HTMLCollections for specific eccentric of factor on the page.
  • Useful for quick access to common grouping of elements like kind, images, or links.

Read More:

What is .find in Javascript?

In JavaScript, .find () is an array method used to search for the 1st element in an array that meets a specific condition.

array.find (callback (element, indicator, array), thisArg)

Here, Callback is a map that tests each constituent. It will return true for the constituent you need to find.

How to Use Selenium With JavaScript to Find Elements?

is a powerful instrument for automating web applications, unremarkably used for examine. With Selenium in JavaScript, you can control browsers and interact with webpage component through the WebDriver API, enable efficient component localisation and manipulation.

For autonomous testing across multiple user personas, check out SUSATest — it explores your app like 10 different real users.

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

1. Prerequisites

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

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

2. Finding Elements in Selenium

Selenium provides various methods to site factor:

  • By ID: findElement (By.id (& # 8220; id & # 8221;))
  • By Class Name: findElement (By.className (& # 8220; className & # 8221;))
  • By Tag Name: findElement (By.tagName (& # 8220; tagName & # 8221;))
  • By: findElement (By.css (& # 8220; selector & # 8221;))
  • By: findElement (By.xpath (& # 8220; xpath & # 8221;))

Must Read:

3. Example Code

Below is an example of using Selenium with JavaScript to open a webpage, find element, 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: Unfastened 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 wait 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 moment); // 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 ();}}) ();

Explanation of the Code

  1. Initialization: A WebDriver instance is created habituate Builder and configure 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 situate using By.name (& # 8220; q & # 8221;), which targets the name property 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 & lt; h3 & gt; element) is loaded.
  6. Fetching Text: The getText () method recover the schoolbook content of the first hunting 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 indispensable for building active and interactive web applications. Once you have accessed HTML elements through the DOM, you can use respective methods to alter their content, attributes, styles, and structure.

Also Read:

Here are the near normally used methods for manipulate elements in JavaScript:

1. Modifying Content

textContent: Updates the plain text inside an element.

Example

document.getElementById (`` model '') .textContent = `` Updated text content! ``;

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

Example

document.getElementById (`` example '') .innerHTML = `` & lt; b & gt; Bold text! & lt; /b & gt; '';

innerText: Similar to textContent but see 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 '');

getAttribute: Retrieves the value of an property.

Example

const altText = document.querySelector (`` img '') .getAttribute (`` alt ''); console.log (altText);

removeAttribute: Removes an attribute.

Example

document.querySelector (`` input '') .removeAttribute (`` disabled '');

3. Manipulating Styles

Inline Styles: Modify CSS forthwith utilise the style property.

Example

document.getElementById (`` box '') .style.backgroundColor = `` blue '';

classList

Manage stratum using method like:

  • add: Adds a class.
  • remove: Removes a form.
  • 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 (`` fighting '');

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

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

Example

const parent = document.getElementById (`` container ''); const child = document.createElement (`` p ''); child.textContent = `` New Paragraph ''; parent.appendChild (child);

remove: Removes an element from the DOM.

Example

document.querySelector (`` # example '') .remove ();

replaceChild: Replaces an existing kid 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);

Best Practices for Finding and Manipulating Elements in JavaScript

When working with the DOM to detect and manipulate elements in JavaScript, follow better practices ensures code readability, maintainability, and performance. Here ’ s a guide to help you act efficaciously:

1. Use Modern DOM Methods

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

Best Practice:

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

Example

const button = document.querySelector (`` .btn ''); const item = document.querySelectorAll (`` .item '');

2. Be Specific with Selectors

Avoid equivocal selectors to assure you place the correct ingredient and trim the risk of selecting unintended single.

Best Practice:

  • Use unique ids when possible for preciseness.
  • Use class name or a combination of CSS chooser for complex queries.

Example

// Good const submitButton = document.querySelector (`` # form .btn-submit ''); // Avoid generic selector like this const button = document.querySelector (`` button '');

3. Minimize DOM Traversals

Repeatedly question the DOM can be high-priced in terms of performance.

Best Practice:

  • Store mention to elements in variable if you need to use them multiple clip.

Example

// Bad: Multiple DOM queries document.querySelector (`` .container '') .classList.add (`` active ''); document.querySelector (`` .container '') .style.color = `` red ''; // Full: Single interrogation, stored reference const container = document.querySelector (`` .container ''); container.classList.add (`` active ''); container.style.color = `` red '';

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 (`` highlighting ''); // Remove a family box.classList.remove (`` nonoperational ''); // Toggle a course box.classList.toggle (`` seeable '');

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 = `` & lt; script & gt; alert ('Hacked! '); & lt; /script & gt; ''; // Safer Alternatives element.textContent = `` Hello, World! ``; const newDiv = document.createElement (`` div ''); newDiv.textContent = `` Safe message ''; element.appendChild (newDiv);

Test JavaScript on Real Devices with BrowserStack

BrowserStack is a cloud-based program for essay JavaScript on real device and browsers. It enables interactiveLive Testingand with popular frameworks like Selenium.

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

Key Benefits of Using BrowserStack for JavaScript Testing:

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

Below are the steps to quiz JavaScript withAutomated Testing:

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

npm install browserstack-local selenium-webdriver

2.Obtain yourUsername and Access Keyfrom the BrowserStack dashboard.

3.Use JavaScript with Selenium to indite 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 capability = {browserName: `` Chrome '', browserVersion: `` latest '', os: `` Windows '', osVersion: `` 10 '', '' browserstack.user '': USERNAME, '' browserstack.key '': ACCESS_KEY,}; (async role 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 component = await driver.findElement (By.css (`` h1 '')); console.log (`` Page Header: '', await element.getText ());} haul (mistake) {console.error (`` Error: '', error);} finally {await driver.quit ();}}) ();
  • Execute the script, and it will run on the choose BrowserStack device.
  • Use BrowserStack Localto test JavaScript on your local development server. Download and install the BrowserStack Local binary to establish a secure connection.
./BrowserStackLocal -- key YOUR_ACCESS_KEY

Once associate, you can test your local web applications on existent device via BrowserStack.

Talk to an Expert

Conclusion

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

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

Frequently Asked Questions

1. How to find an element in an target in JavaScript?

To find an element in an objective in JavaScript, you can use a loop or Object.values (), Object.keys (), or Object.entries () with .find ().

const obj = {a: {id: 1, name: `` Alice ''}, b: {id: 2, name: `` Bob ''}}; const result = Object.values (obj) .find (item = & gt; item.name === `` Bulb ''); console.log (result); // {id: 2, name: `` Bulb ''}

2. How to control if the ingredient is found in JavaScript?

To check if an element is found in JavaScript, use a condition:

if (result) {// Element found} else {// Not found}

Or You could explicitly check:

if (result! == undefined) {// Found}

Utile Resources for Javascript

Tags
71,000+ Views

# Ask-and-Contributeabout this topic with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free