JavaScript function getElementsByName


javascript JavaScript function getElementsByName Javascript Function

How to get access to HTML element by using attribute ' name ' of HTML tag?

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.

How can we access a specific HTML tag using getElementsByName?

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>

Alert the input value and span content using onclick function,getElementsByName

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

Output of Below Source Code

I am a Span Content
<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>
javascript Javascript Function Chapter Next »