JavaScript function getElementsByClassName


How to get access to HTML element by using Class name?

First we should have knowledge about the difference between the Class and ID. • - An ID is a unique identifier , and it will exist on page with unique value. We can assign one unique ID to only one HTML tag. • - However we can apply Class to multiple HTML tag.

How can we access a specific HTML tag using getElementsByClass?

We use the HTML tag index. In below code there are two HTML tag div and span with same class='myClass'

. <div class="myClass"> I am at index 0</div> <span class="myClass">I am at index 1</span>

Above Two HTML tags can be access by following way.

<script type="text/javascript"> var firstIndexData = document.getElementsByClassName("myClass")[0]; // For Div Tag var secondIndexData = document.getElementsByClassName("myClass")[1]; // For Span Tag </script>

Alert the div and span content using onclick function

Note. For fetching the inner data of HTML tag we will use the keyword innerHTML

OutPut of Below Code

<div class="myClass"> I am at index 0</div> <span class="myClass">I am at index 1</span> <button onclick="firstFunction()">MyClass Data 1 </button> <button onclick="secondFunction()">MyClass Data 2 </button> <script type="text/javascript"> function firstFunction() { var firstIndexData = document.getElementsByClassName("myClass")[0].innerHTML; // For Div Tag alert(firstIndexData); } function secondFunction() { var secondIndexData = document.getElementsByClassName("myClass")[1].innerHTML; // For Span Tag alert(secondIndexData); } </script>
Chapter Next »