DOM methods


1. getElementById() method

The getElementById() method returns the element of the specified id.

It returns the element as an object but if the element is not found, it returns null.

Syntax:

    document.getElementById(“id”);


Example:

    <p id=”example”></p>
    <p id=”example2”></p>
    <script>
        document.getElementById(“example”).innerText = “This is an example of getElementById.”;
    </script>

The above example first gets the paragraph element by its id (i.e. example) and then changes its text through innerText property. The paragraph with id as example2 will remain unaffected.


2. getElementsByTagName() method

The getElemenstByTagName() method returns all the elements of the specified tag name.

Syntax:

    document.getElementsByTagName(“tagName”);


Example:

    <p>This is paragraph1.</p>
    <p>This is paragraph2.</p>
    <p>This is paragraph3.</p>
    <button onclick=”numpara()”>Number of paragraphs</button>
    <script>
        function numpara()
        {
            var total = document.getElementsByTagName(“p”);
            document.write(“Total number of p tags are: ” + total.length); // prints 3
        }
    </script>    



3. getElementsByName() method

The getElementsByName() method returns all the elements of the specified name.

Syntax:

    document.getElementsByName(“Name”);


Example:

    <form>
    Yes: <input type=”radio” name=”choice”>
    No: <input type=”radio” name=”choice”>
    <button onclick=”nameElements”>Total choices</button>
    </form>
    <script>
        function nameElements()
        {
            var ch = document.getElementsByName(“choice”);
            document.write(“Total choices: “ + ch.length); // prints 2
        }
    </script>