JavaScript > Dealing with HTML Controls

Finding HTML element by name in JavaScript

How to find a HTML element from using it’s name attribute in JavaScript?


To find out the html elements by their tag names, we can follow this approach.

    <script>
        function TestFunction() {
            document.getElementsByTagName("label")[0].innerHTML = 50;
        }
    </script>

    <label id="lblText">0</label>
    <label id="Label1">0</label>
    <input type="button" id="btnTest" onclick="TestFunction()" value="Click me" />

This is used to find all the elements of the page using the tag name. It returns all the elements in the form of array.

In the above function, getElementsByTagName finds all html elements by tag name. “length” property can be used to know the number of elements found on the page and indexer can be used to access a particular element.

In the above code snippet, we are retrieving the first label (with indexer 0) of the page and setting its innerHTML to 50.

OUTPUT

 Views: 4302 | Post Order: 58



Write for us






Hosting Recommendations