HTML DOM getElementsByClassName() Method

The getElementsByClassName() method returns a collection of all elements in the document with the specified calss name, as a NodeList object. The nodes at Nodelist can be accessed by index numbers. The syntax of getElementsByClassName() is :
  document.getElementsByClassName(ClassName);
Example :
<html>
<body>
  <p class="para">This is Paragraph One</p>
  <p class="para">This is Paragraph Two</p>
  <p class="para">This is Paragraph Three</p>
  <div class="para">This is the text inside the DIV</div>
  <ul id="list" class="mylist">
    <li>First List</a></li>
    <li>Second List</a></li>
    <li>Third List</li>
    <li>Fourth List</li>
  </ul>
  <button onclick="func1()">Click Here</button>
  <button onclick="func2()">Click Here</button>
  <div id="div1"></div>
  <script>
    function func1() {
      var elem = document.getElementsByClassName('para');
      var text = "Number of Elements with class '<b>para</b>' : " + elem.length;
      text += "The innerText of elements are : ";
      for(var x = 0; x < elem.length; x++) {
        text += document.getElementsByClassName('para')[x].innerText;
      }
      document.getElementById('div1').innerHTML = text;
    }

    function func2() {
      var elem = document.getElementsByClassName('mylist');
      var text = "Number of Elements with class '<b>mylist</b>' : " + elem.length;
      text += "The innerText of elements are : ";
      var text1;
      for(var x = 0; x < elem.length; x++) {
        text += document.getElementsByClassName('mylist')[x].innerText;
      }
      document.getElementById('div1').innerHTML = text;
    }
  </script>
</body>
</html>
Output :

This is Paragraph One
This is Paragraph Two
This is Paragraph Three
This is the text inside the DIV
  • First List
  • Second List
  • Third List
  • Fourth List



At here the first function will print the number of elements with class 'para' and the innerText of all those elements. And the second function will do the same thing with the elements which is in class 'mylist'.


Next Topic :