JavaScript function getElementsByTagName


javascript JavaScript function getElementsByTagName Javascript Function

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

Similarly like getElementsByName and getElementsByClass we will need to use the index in getElementsByTagName also.
  1. As we know that ID is a unique identifier , and we can only assign unique ID value to HTML tag .
  2. 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 getElementsByTagName?

We are going to create the two paragraph and then we will access them by their index using getElementsByTagName. <p> Courtesies cannot be borrowed like snow shovels; you must have some of your own. </p> <p> A reformer is one who brings reforms in the society.</p>

JavaScript Function to get element by Tag name

<script type="text/javascript"> function paragraph_first() { var paragraph = document.getElementsByTagName('p')[0].innerHTML; // First <p> alert(paragraph); } function paragraph_second() { var paragraph = document.getElementsByTagName('p')[1].innerHTML; //// Second <p> alert(paragraph); } </script>

Output of Javascript Function getElementByTagName

Courtesies cannot be borrowed like snow shovels; you must have some of your own.

A reformer is one who brings reforms in the society.

Full Source Code of JavaScript Function getElementsByTagName

<button onclick="paragraph_first()"> Click For First Paragraph </button> <button onclick="paragraph_second()"> Click For Second Paragraph </button> <p> Courtesies cannot be borrowed like snow shovels; you must have some of your own. </p> <p> A reformer is one who brings reforms in the society.</p> <script type="text/javascript"> function paragraph_first() { var paragraph = document.getElementsByTagName('p')[0].innerHTML; // First <p> alert(paragraph); } function paragraph_second() { var paragraph = document.getElementsByTagName('p')[1].innerHTML; //// Second <p> alert(paragraph); } </script>
javascript Javascript Function Chapter Next »