Skip to content
Advertisements

Document.getElementsByTagName()

With the “getElementsByTagName” method we can access the html tags.

var elements = document.getElementsByTagName(name);

“document.getElementById()” difference:

Thanks to “document.getElementById() ” we could reach the tags with id.

With the “getElementsByTagName” method we can access the html tags.

id is given a single value. But the labels are not the only one. A code array can be used more than the same label. So when we use “getElementsByTagName”, if there are more than one of the same tag, we need to show which one we choose. We do this as shown below.

<p id="par1"></p>
<p id="par2"></p>
<p id="par3"></p>

 <script>
        // id=par1
        param1 = document.getElementsByTagName("p")[0];

        // id=par2
        param2 = document.getElementsByTagName("p")[1];

        // id=par3
        param3 = document.getElementsByTagName("p")[2]; 
 </script>

Example-1

Document.getElementsByTagName()
    <div id="container">
        <p id="par1">I am javaScript</p>
        <p id="par2">I am not javaScript</p>
        <p id="par3">We are javaScript</p>
    </div>
    <button onclick="show();">SHOW</button>

    <script>
        function show() {
            var a = document.getElementById("container");
            var b = a.getElementsByTagName("p");
            a.style.background = "red";
            var i;
            for (i = 0; i < b.length; i++) {
                b[i].style.fontWeight = "bold";
            }
        }

    </script>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: