Monday, January 30th, 2006

getElementsByTagNames: note the plural

Category: Examples, JavaScript, Utility

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.



  1. // 1
  2. var headerList = getElementsByTagNames('h1,h2,h3,h4');
  4. // 2
  5. var element = document.getElementById('test');
  6. var formFieldList = getElementsByTagNames('input,select,textarea',element);


(from quirksmode)

function getElementsByTagNames(list,obj) {
if (!obj) var obj = document;
var tagNames = list.split(‘,’);
var resultArray = new Array();
for (var i=0;i

Posted by Dion Almaer at 1:02 pm

4.2 rating from 34 votes


Comments feed TrackBack URI

IE and the standards are going to drop getElementsByTagName, will they continue support of ~ByTagNames?


Comment by Daniel — January 30, 2006

Anything that builds upon the DOM goes down as a swiss-army function in my book. This is a great function indeed :)

Comment by Dustin Diaz — January 30, 2006

Here is a little shortcut:
push appends arrays :)

Comment by Max — January 31, 2006

To actually have it comply with specs and take a list, and not just a string, replace the list.split(',') bit with typeof list=='string' ? list.split(',') : list so 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.

Comment by Johan Sundström — January 31, 2006

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

Comment by Johan Sundström — January 31, 2006

Anything that builds upon the DOM goes down as a swiss-army function in my book. This is a great function indeed :)

Comment by backgammon game — June 15, 2006

Leave a comment

You must be logged in to post a comment.