Get elements by class name in javascript

To get elements using class name we use getElementsByClassName method available with document object. This method takes name of class an argument. 
It returns array of elements because more than one element(s) can have same class.

<input type="button" value="Get By Class" onclick="GetByClassName()" />
<div id="myDiv" class="myClass">
    This is a div
</div>

<script type="text/javascript">
 function GetByClassName() {
        var elements = document.getElementsByClassName("myClass");
        if (elements.length > 0) {
            alert(elements[0].innerHTML);
        }
    else
      alert("No matching element found");
   }
 </script>


Comments

Popular posts from this blog

Check if ViewBag is null or doesn't exist

Using Progress Bar In C#

Jquery serer side datatables in asp.net