CancelImage Upload

Changing style, properties and content of multiple tags with getElementsByTagName

I have frequently discussed how the JavaScript function getElementById() can be used to access an individual HTML tag, and manipulate it's content, styles and properties. And while this function more than fulfils the requirements for accessing an individual HTML element, what if we wanted to access a specific set of tags, let's say every span tag within our document?

Here then another function is needed. To load a specific set of HTML tags we will need the services of getElementsByTagName, which will load each specified tag as an object array into a specified variable:

var spanTags = document.getElementsByTagName("span");

As with getElementById(), we can now use this array of span objects to access or manipulate information within every span tag on the page. In the following example for instance we will simply load the name and content of every span tag within the HTML document's body:

<title>How to access individual HTML Tags</title>
<script type="text/javascript">
function loadElementsByName()

        var status = "<b>Content and names of span tags:</b><br><br>";

        var st =document.getElementsByTagName("span");

        for(i = 0; i != st.length; i++)

                status = status + st[i].name + ": " + st[i].innerHTML + "<br>";


        document.getElementById("status").innerHTML = status;

<body onload="loadElementsByName()">

<span name="span1">This is the content of span 1</span><br>
<span name="span2">This is the content of span 2</span><br>
<span name="span3">This is the content of span 3</span><br>
<div id="status"></div>


Want to leave a comment?

No problem. Just enter your email and password below.

register | home | reminder

myDesignTool Networking •