Open In App

How to get elements of specific class inside a div ?

Last Updated : 09 Apr, 2021
Like Article

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.



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.


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

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