Open In App

How to get elements of specific class inside a div ?

Last Updated : 09 Apr, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will find how to get all elements of a specific class inside an HTML div tag.

To do this we will use HTML DOM querySelectorAll()method. This method of HTML DOM (document object model) returns all elements in the document that matches a specified CSS selector(s). The syntax to use this method is as follows.

Syntax:

document.querySelectorAll(CSS-selectors)

Example: The CSS selectors would be class, ids, or any HTML tags. Let us learn how to use this method to select elements of a specific class inside an HTML div tag.

HTML




<!DOCTYPE html>
<html>
  <head>
    <style>
      #tag {
        border: 4px solid black;
        margin: 5px;
      }
    </style>
  </head>
  <body>
    <div id="tag">
      <p class="example1">HTML</p>
  
      <p class="example1">CSS</p>
  
      <p class="example1">Javascript</p>
  
      <p class="example2">C</p>
    </div>
    <br />
  
    <button onclick="changecolor()">
      click to Apply change
    </button>
    <script>
      function changecolor() {
        var x = document.getElementById("tag")
                .querySelectorAll(".example1");
        for (i = 0; i < x.length; i++) {
          x[i].style.backgroundColor = "blue";
        }
      }
    </script>
  </body>
</html>


Output:After clicking the “click to Apply change” button, we get the following output. We can see that by selecting a div using getElementById() and then selecting all its elements inside the div using querySelectorAll(), we can apply changes to all its elements.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads