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.
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>
Note. For fetching the inner data of HTML tag we will use the keyword innerHTML
<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>