Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Using getElementById, querySelector, and Other DOM Methods in JavaScript


In JavaScript, there are several methods to access and manipulate HTML elements within the DOM (Document Object Model). These methods allow you to dynamically change the content, style, and attributes of elements. In this article, we’ll discuss commonly used DOM selection methods such as getElementById, getElementsByClassName, getElementsByTagName, querySelector, and querySelectorAll with examples for each.

1. getElementById()

The getElementById() method selects an element based on its unique id attribute. It returns a single element or null if the element is not found.

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

          <script>
              let header = document.getElementById("header");
              console.log(header); // Outputs the <div> element with id="header"
              header.textContent = "Welcome!";
              // Changes content to "Welcome!"
          </script>
      

In this example, getElementById("header") retrieves the <div> element with the ID "header" and changes its text content to "Welcome!"

2. getElementsByClassName()

The getElementsByClassName() method selects all elements with a specified class name. It returns a live HTMLCollection, which updates automatically if elements with the specified class are added or removed from the document.

          <div class="item">Item 1</div>
          <div class="item">Item 2</div>

          <script>
              let items = document.getElementsByClassName("item");
              console.log(items); // Outputs all elements with class "item"
              
              for (let i = 0; i < items.length; i++) {
                  items[i].textContent = "Updated Item " + (i + 1);
              }
              // Changes content of each item to "Updated Item 1", "Updated Item 2", etc.
          </script>
      

Here, getElementsByClassName("item") selects all elements with the class "item" and modifies their text content.

3. getElementsByTagName()

The getElementsByTagName() method selects all elements with a specified tag name (e.g., div, p, span). It returns an HTMLCollection of elements with that tag name.

          <p>Paragraph 1</p>
          <p>Paragraph 2</p>

          <script>
              let paragraphs = document.getElementsByTagName("p");
              console.log(paragraphs); // Outputs all <p> elements
              
              for (let i = 0; i < paragraphs.length; i++) {
                  paragraphs[i].style.color = "blue";
              }
              // Changes text color of each paragraph to blue
          </script>
      

In this example, getElementsByTagName("p") selects all <p> elements and sets their text color to blue.

4. querySelector()

The querySelector() method selects the first element that matches a specified CSS selector. This method is useful for selecting elements based on complex criteria, like tag, class, or ID combinations.

          <div class="container">
              <p>Paragraph 1</p>
          </div>
          <p>Paragraph 2</p>

          <script>
              let firstParagraph = document.querySelector(".container p");
              console.log(firstParagraph); // Outputs the first <p> inside .container
              firstParagraph.textContent = "Updated Paragraph";
              // Changes content to "Updated Paragraph"
          </script>
      

In this example, querySelector(".container p") selects the first <p> element inside an element with the class "container" and updates its text content.

5. querySelectorAll()

The querySelectorAll() method selects all elements that match a specified CSS selector and returns a static NodeList. Unlike HTMLCollection, a NodeList doesn’t update automatically when the document changes.

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

          <script>
              let boxes = document.querySelectorAll(".box");
              console.log(boxes); // Outputs all elements with class "box"
              
              boxes.forEach(function(box, index) {
                  box.textContent = "Box " + (index + 1);
              });
              // Sets content of each box to "Box 1", "Box 2", etc.
          </script>
      

Here, querySelectorAll(".box") selects all elements with the class "box" and updates their text content using forEach to iterate over the NodeList.

Summary

Each of these DOM selection methods has unique properties and use cases:

Understanding these methods helps you effectively manipulate the DOM in JavaScript, making your web pages more interactive and dynamic.





Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java