W3C home > Mailing lists > Public > www-dom@w3.org > July to September 2001

Req: Include document.getElementsByAttrMatch()

From: Alexander J. Vincent <ajvincent@hotmail.com>
Date: Thu, 26 Jul 2001 08:07:28 -0700
To: www-dom@w3.org
Message-ID: <F168zdDW6lCPx33E1io00006545@hotmail.com>
Reposted from http://bugzilla.mozilla.org/show_bug.cgi?id=92362 , and edited 
to remove references to Mozilla:

A common practice of HTML documents is using the same name or id attribute 
value across multiple elements to create arrays for JavaScript or 
server-side code:

<input name="myInput[]" />
<input name="myInput[]" />

XML 1.0 and XHTML 1.0 disallow this, by the Document Type Definition.  So 
there's no direct way to grab a specifically limited set of the desired 
elements without coding in a special function.  In any case, I would love 
the ability ... to find elements by attribute names in general, matched to a 
regular expression.  This would allow us to select a group of elements much 
more specifically than DOM Level 1 (and 2) methods allow.

...Here is a JavaScript function which may closely approximate what would be 
needed to enable this.

document.getElementsByAttrMatch = function(attrName, attrMatch) {
	attrName = attrName.valueOf()
	attrMatch = attrMatch.valueOf()
// in case the user passes String() and RegExp() objects

	if ((typeof attrName != "string")||(typeof attrMatch != "regexp") {
// arguments must be correct

	var response = new NodeList(), elementList = 
document.getElementsByTagName("*"), loop=0
// set up basic parameters

	for (loop=0; loop < elist.length; loop++) {
		if (attrMatch.test(elementList[loop].getAttribute(attrName))) {
// if the attribute named has its value match the regular expression to 
for, add it to the array
			response[response.length] = elementList[loop]
	return response

As an extra, since we like to get elements by id as well, I would suggest 

document.getElementsByIdMatch = function(idMatch) {
	return document.getElementsByAttrMatch('id', idMatch)

I regret I'm not able to immediately provide namespace-enabled  equivalents 
to these functions.  Opinions?

Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp
Received on Thursday, 26 July 2001 11:07:59 UTC

This archive was generated by hypermail 2.3.1 : Tuesday, 20 October 2015 10:46:08 UTC