|
Help
CodingForums Partners
This is a
![]() |
Creating custom collections in the DOM (via ID attribute)Browsers that support DOM Level 2 such as IE6 and Firefox have a few methods for retrieving elements on the page. The two most prominent ones are: -document.getElementById(idname) -document.getElementsByTagName(tagname) whereby the first method retrieves an element with a specific ID, and the second fetches all elements of a particular TAG. But what if you want to collect arbitrary elements on the page to perform manipulation on them, such as 2 DIVs and 3 Paragraphs?. In IE6+, such a task can be accomplished by assigning the same ID to the elements you wish extracted, and then using document.all to retrieve them: <img src="1.gif" id="test"> <b>Hello</b> <span id="test">There</span> <script type="text/javascript"> document.all.test.length //returns 2 document.all.test[0] //returns <img src="1.gif"> </script> This is a very simple way to create custom collections in IE. However, it does violate one of the unforgiveable sins of the DOM, by giving two or more elements the same ID value. The DOM specifies that the ID attribute should contain a unique value for each element that uses it. And of course, this method for creating custom collections only works in IE, not Firefox.
|