Derek Basch wrote:
[...]
> Crazy second thought....
>
> Why couldnt the class attribute be used as the selector? The id
> attribute is already used as a selector in both the DOM and CSS
> contexts. And isnt the idea of a class:
>
> a collection of things sharing a common attribute; "there are two
> classes of detergents"
> http://www.cogsci.princeton.edu/cgi-...e=1&word=class
>
Not really so crazy. the HTML 4.01 spec says:
Quote:
class = list
This attribute assigns a class name or set of class names to
an element. Any number of elements may be assigned the same
class name or names. Multiple class names must be separated
by white space characters.
Animatable: yes.
The class attribute assigns one or more class names to an
element. The element may be said to belong to these classes.
A class name may be shared by several element instances. The
class attribute has several roles:
* As a style sheet selector (when an author wishes to assign
style information to a set of elements).
* For general purpose processing by user agents.
|
Which would seem to suggest that class should be able to be used
exactly as you have described.
I understand Mike's point that it is fairly trivial to use
getElementsByTagName then process them to roll-your-own
collection (actually by building an array you get something more
versatile than a collection anyway), but it gets more complex if
you have to get different element tags so you may have to
recurse down all the children of the body tag to get what you
want.
As an interim measure, why not write your own
getElementByClassName() that does exactly that? Here's a start
below. It should be possible to declare the cArray in the
initial function, then make the recursion routine an internal
function (gets away from global array).
Also when testing the match of the class name, it needs to use a
regular expression to match the class as part of a
space-delimited string (i.e. the element may have multiple class
names).
I'll leave that up to you (or Mike, if he's still watching).
Uncomment the debug to watch the nodes being processed.
No doubt this can be optimised further, but I think you get the
idea. Properly optimised, it is perhaps 6 or 7 lines of code.
<html><head>
<title>getElementsByClassName</title>
<script type="text/javascript">
function getElementsByClassName(c) {
cArray = []; // Global scope intentional
var n = document.getElementsByTagName('body')[0];
doTree(n,c);
return cArray;
}
function doTree(n,c) {
if (n.className && n.className == c)
cArray.push(n);
// Some debug...
// var ct = (n.className)? n.className : 'no class';
// alert(n.nodeName + ' : ' + ct);
for (var i=0; i<n.childNodes.length; i++) {
doTree(n.childNodes[i],c);
}
}
</script>
</head>
<body>
<input type="button" value="Click me" onclick="
var robArray = getElementsByClassName('rob');
alert(robArray.join('\n'));
">
<p class="rob">rob para</p>
<p class="rob">rob para2</p>
<div class="rob">rob div</div>
<div class="rob">rob div2</div>
</body>
</html>
--
Rob