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

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
Microsoft Shows Off Silverlight 4, IE9 Plans
Metasploit Expands Vulnerability Test Framework
HyperCard Reborn?

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:

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
Rolling Out Your Own HTML Application Version Control · HTML 5: Client-side Storage · Working with Ajax Server Extensions
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Wi-Fi Product Watch, November 2009 · Chip Market Recovering From '08 Collapse · Low-Cost Tools to Kickstart Your New Business