Monday, January 30th, 2006
getElementsByTagNames: note the plural
<p>Peter-Paul Koch has created a new script which implements getElementsByTagNames.HTML has several related elements with distinct tag names, like h1-h6 or input, select and textarea. getElementsByTagName works only on elements with the same tag name, so you cannot use it to get a list of all headers or all form fields.
The getElementsByTagNames script (note the plural "names") takes a list of tag names and returns an array that contains all elements with these tag names in the order they appear in the source code. This is extremely useful for, for instance, my ToC script, which needs all h3s and h4s in the document in the correct order.
I'd have loved to add this method to the Node prototype, but that's impossible in Explorer and Safari. Therefore I use it as a normal function until all browsers expose their W3C DOM prototypes.
Examples
-
-
// 1
-
var headerList = getElementsByTagNames('h1,h2,h3,h4');
-
-
// 2
-
var element = document.getElementById('test');
-
var formFieldList = getElementsByTagNames('input,select,textarea',element);
-
Implmentation
(from quirksmode)
-
-
function getElementsByTagNames(list,obj) {
-
if (!obj) var obj = document;
-
var tagNames = list.split(',');
-
var resultArray = new Array();
-
for (var i=0;i<tagNames.length;i++)
-
{
-
var tags = obj.getElementsByTagName(tagNames[i]);
-
for (var j=0;j<tags.length;j++)
-
{
-
resultArray.push(tags[j]);
-
}
-
}
-
var testNode = resultArray[0];
-
if (testNode.sourceIndex)
-
{
-
resultArray.sort(function (a,b) {
-
return a.sourceIndex - b.sourceIndex;
-
});
-
}
-
else if (testNode.compareDocumentPosition)
-
{
-
resultArray.sort(function (a,b) {
-
return 3 - (a.compareDocumentPosition(b) & 6);
-
});
-
}
-
return resultArray;
-
}
-
Related Content:











IE and the standards are going to drop getElementsByTagName, will they continue support of ~ByTagNames?
dk
Anything that builds upon the DOM goes down as a swiss-army function in my book. This is a great function indeed :)
Here is a little shortcut:
resultArray.push(obj.getElementsByTagName(tagNames[i]));pushappends arrays :)To actually have it comply with specs and take a list, and not just a string, replace the
list.split(',')bit withtypeof list=='string' ? list.split(',') : listso you can actually pass an array too. But first make sure you replace Ajaxian’s typographic apostrophes with real apostrophes or quotation marks, or the code will not even parse.Or, actually, strike that last bit about typographic quotes; as it turns out, Ajaxian’s Live Preview, isn’t. (It shows some other variant of your comment than what goes live when you submit it. Which, at least to me, kind of reduces funcitonality into misleading eye candy.)
Anything that builds upon the DOM goes down as a swiss-army function in my book. This is a great function indeed :)