Skip to content
Related Articles

Related Articles

Improve Article

How to get elements of specific class inside a div ?

  • Last Updated : 09 Apr, 2021

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.

Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :