...

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



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

dep

jkd
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.

Kor
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++){
if(el[i].getAttribute(fauxAtt)!=null){
... do something ...
}
}
}

for instance:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<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(){
findGrouped('foo');
}
function findGrouped(fauxAtt){
var el = document.getElementsByTagName('*');
for(var i=0;i<el.length;i++){
if(el[i].getAttribute(fauxAtt)!=null){
alert(el[i].innerHTML)
}
}
}
</script>
</head>
<body>
<span>one</span>
<span>two</span>
<div foo>has foo Attribute</div>
<span>three</span>
<span foo>has also a foo Attribute</span>
<span>four</span>
</body>
</html>


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...)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum