September 21, 2000 - Scripting Multiple Elements with the Same ID | WebReference

September 21, 2000 - Scripting Multiple Elements with the Same ID

Yehuda Shiran September 21, 2000
Scripting Multiple Elements with the Same ID
Tips: September 2000

Yehuda Shiran, Ph.D.
Doc JavaScript

For certain applications, you may want to have multiple HTML elements with the same ID in a single document. And then, you want to distinguish between them for scripting and other purposes. The following elements, for example, have the same ID, "common":

This is the first common element of the page
This is the second common element of the page They are defined as follows:

<DIV ID="parent1">
  <DIV ID="common">This is the first common element of the page</DIV>
</DIV>
<SPAN ID="parent2">
  <SPAN ID="common">This is the second common element of the page</SPAN>
</SPAN>

The key relevant object in Internet Explorer is document.all. By using document.all(elementID) you can quickly find and access every element in the document. The following JavaScript expression will return the number of elements in the document with ID="common":

document.all("common").length

Once you know how many elements you are looking for, you can iterate over them. The following JavaScript script prints the element types of those with ID="common":

function printCommon() {
  elementCount = document.all("common").length;
  for (i=0; i<elementCount; i++) {
    alert("Next element is of type " + document.all("common",i).nodeName);
  }
}

Try it. You can see from the types shown that indeed the two different elements are accessed.