Similarly like getElementsByClass we will need to use the index. • - As we know that ID is a unique identifier , and we can only assign unique ID value to HTML tag . • - However we can apply Class and Name attribute with same name and class attribute value to the multiple HTML tags. We use the INDEX to get access the HTML tags.
We are going to create two HTML tags <input> and <span> with same name='CodingMagic'
.<input value="Codingpk@CodingPK.com" type="email" name="CodingMagic"/>
<span name="CodingMagic">I am a Span Content</span>
Above Two HTML tags can be access by following way.
<script type="text/javascript">
var firstIndexData = document.getElementsByName("CodingMagic")[0]; // For input Tag
var secondIndexData = document.getElementsByName("CodingMagic")[1]; // For Span Tag
</script>
Note. For fetching the value of input field we will use the keyword value and for inner data of HTML tag we will use the keyword innerHTML
<input value="Codingpk@CodingPK.com" type="email" name="CodingMagic"/>
<span name="CodingMagic">I am a Span Content</span>
<button onclick="firstFunction()">Input Tag Value </button>
<button onclick="secondFunction()">Span Tag Content</button>
<script type="text/javascript">
function firstFunction()
{
var firstIndexData = document.getElementsByName("CodingMagic")[0].value; // For input Tag
alert(firstIndexData);
}
function secondFunction()
{
var secondIndexData = document.getElementsByName("CodingMagic")[1].innerHTML; // For Span Tag
alert(secondIndexData);
}
</script>