Locating elements in the DOM exclusively through relationship properties can be tricky. Lists, for example, have more children than you'd expect.

You'd think an unordered list (UL) with three list items (LI) would have 3 children. But in Mozilla, such a list has these 7 children. In Internet Explorer 6, the same list has these 4 children. Because of such variations, properties like childNodes, firstChild, nextSibling, etc., aren't always dependable.

However, the DOM provides 2 reliable ways to locate elements in a document.

getElementById() Find an element with an assigned ID.
If the first paragraph were assigned the ID "intro" (ex: <p id="intro">), you could locate it this way:


Since ID's are unique within a page, only DOCUMENT possesses this method — it would be redundant elsewhere. It's the simplest way to find a specific element, but it isn't the best tool in every case.

getElementsByTagName() Get a list of elements.
You may need to locate all the links in a document, and it would be cumbersome to assign each a unique ID. Instead, you can ask DOCUMENT to search its descendents for all A elements:


This creates a list, starting with 0, through which you can find specific elements:

document.getElementsByTagName("a")[0]  the 1st anchor
document.getElementsByTagName("a")[1]  the 2nd anchor

When you need to work with an element, or list of elements, you generally create a reference to it to save yourself a lot of typing (and possible typos), and to avoid redundant searches of your page. The code below creates a variable, "Alist," to act as a shorthand reference to the list of A elements:

var Alist = document.getElementsByTagName("a");  "alist" = list of all A elements
var A0 = Alist[0];  A0 = the 1st anchor
var A1 = Alist[1];  A1 = the 2nd anchor

Every element contains a "getElementsByTagName()" method. This allows you to control the extent, or "scope," of your results. Consider the differences between these 2 bits of code:

var LIs = document.getElementsByTagName("li");  finds ALL list items in document

var mylist = document.getElementsByTagName("ul")[0];  mylist = 1st UL
var LIs = mylist.getElementsByTagName("li");  finds list items only in mylist

Finally, you can combine both strategies — find an element by ID, then search it by tag name:

var mylist = document.getElementById("menu");  
var LIs = mylist.getElementsByTagName("li")

Once you've found an element, you're ready to put it to work.