View Full Version : How many elements on the page have the same ID?

01-10-2006, 05:52 PM
How can I find out how many elements on the page have the same ID?


01-10-2006, 06:18 PM
Technically, only at most 1 element may have a particular id. If two or more elements share the same id, then it is a violation of the DTD specification for the id attribute (IDREF).

A better way to group items is either by the class attribute or by the name attribute. If you use the name attribute, then document.getElementsByName("thename").length returns the number of elements with that name.

If you don't mind invalid markup and IE-only, then you can keep the id's and use document.all["theid"].length to determine the number of elements with the same id.

01-11-2006, 11:47 AM
Maybe it does not fit exactly to this thread but...

Sometimes it may happen that you need to group some elements but you can not use id (as id must be unique) nore name (for different reasons, you need them to have different names) nor classNames (for different reasons you need them to have different classes) nor tagname (they might have different tag names).

This case there might be another tricky way to group those such different elements, by using a "faux attribute" (make sure it is not a HTML or Javascript reserved word).

function findGrouped(fauxAtt){
var el = document.getElementsByTagName('*');//here's a wild card
for(var i=0;i<el.length;i++){
... do something ...

for instance:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/javascript">
onload = function(){
function findGrouped(fauxAtt){
var el = document.getElementsByTagName('*');
for(var i=0;i<el.length;i++){
<div foo>has foo Attribute</div>
<span foo>has also a foo Attribute</span>

It might be used for instance when validate different required elements in a form, which must have different names (or ids), have different classes and have different tag names (input, textarea...)