document.getElementsByTagName
returns an array of elements corresponding to a tag which is provided to the function as a parameter. The code outputs undefined
to the console because testDiv
is not an HTML tag. When using getElementsByTagName
the script gets elements based upon the name (think type) of their tag, so names like div,span,ul,li,input,etc.
For example, document.getElementByTagName("div")
will return all div
elements on the page. It does not inspect the name attribute on a tag and return corresponding elements.
Here are a few examples to demonstrate the proper usage of these methods, they rely on your provided HTML:
//Retrieves Element By ID
var element = document.getElementById("testDiv");
alert("By Id: " + element.innerHTML);
//Retrieves By Tag
var element2 = document.getElementsByTagName("div");
//Remember this is an array we must specify an index
alert("By Tag Name: " + element2[0].innerHTML);
var doesntWork = document.getElementsByTagName("testHolder");
alert("By Tag Name: " + doesntWork[0].innerHTML);//Won't work
Demonstration: http://jsfiddle.net/TEJKB/
Make sure your executing this script after the DOM has loaded. For a simple test, place this script at the bottom of your page. If that works then you need to add an event handler to the window.onload
event.