Question

How do I get an element or element list by it's tag name. Take for example that I want all elements from <h1></h1>. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­

Was it helpful?

Solution

document.getElementsByTagName('a') returns an array. Look here for more information: http://web.archive.org/web/20120511135043/https://developer.mozilla.org/en/DOM/element.getElementsByTagName

Amendment: If you want a real array, you should use something like Array.from(document.getElementsByTagName('a')), or these days you'd probably want Array.from(document.querySelectorAll('a')). Maybe polyfill Array.from() if your browser does not support it yet. I can recommend https://polyfill.io/v2/docs/ very much (not affiliated in any way)

OTHER TIPS

Use $$() and pass in a CSS selector.

Read the Prototype API documentation for $$()

This gives you more power beyond just tag names. You can select by class, parent/child relationships, etc. It supports more CSS selectors than the common browser can be expected to.

Matthias Kestenholz:

getElementsByTagName returns a NodeList object, which is array-like but is not an array, it's a live list.

var test = document.getElementsByTagName('a');
alert(test.length); // n
document.body.appendChild(document.createElement('a'));
alert(test.length); // n + 1

You could also use $$(tag-name)[n] to get specific element from the collection.

If you use getElementsByTagName, you'll need to wrap it in $A() to return an Array. However, you can simply do $$('a') as nertzy suggested.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top