Johnny
Johnny

Reputation: 437

Prototype get by tag function

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

Upvotes: 1

Views: 8883

Answers (5)

Matthias Kestenholz
Matthias Kestenholz

Reputation: 3348

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)

Upvotes: 6

Trython
Trython

Reputation: 11

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

Upvotes: 1

Caged
Caged

Reputation: 963

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.

Upvotes: 0

eyelidlessness
eyelidlessness

Reputation: 63519

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

Upvotes: 1

Grant Hutchins
Grant Hutchins

Reputation: 4409

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.

Upvotes: 4

Related Questions