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

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
Eclipse Helios Update Brings New PHP Tools
Internet Explorer 9 Ups Standards Support
JBoss Portal 5 Release Easier to Use

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.


People who read this tip also read these tips:

Look for similar tips by subject:

webref The latest from WebReference.com Browse >
Flashmaps' DynamicLocator: Interactive Maps for Small Areas · Flashmaps' AreaSelector: Interactive Maps for Wide Areas · The DB Mapper: Interactive Street-level Maps of U.S. and Canada
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
MS Access and MySQL · Cisco AutoQoS: VoIP QoS for Mere Mortals · While VoIP Adoption Explodes in Enterprise, Carrier Spending Lags