A Better Answer
I now recommend this answer by Tim Kindberg to the question Get all Attributes from a HTML element with Javascript/jQuery that uses getAttributeNames()
and getAttribute(name)
, which MDN says "is a memory-efficient and performant alternative to accessing Element.attributes
."
Use Array.from()
or Spread Operator ...
Update: Array.from()
and Spread operator ...
were added to ECMA-262 6th Edition in June 2015, which now has universal modern browser support.
See MDN › Array.from() & Spread syntax (...)
var elem = document.getElementById('input'),
attrs = elem.attributes;
console.log('Array.from(attrs)');
Array.from(attrs).forEach(({ name, value }) => {
console.log(` ${name}: ${value}`);
})
console.log('[...attrs]');
[...attrs].forEach(({ name, value }) => {
console.log(` ${name}: ${value}`);
})
<input type='button' onClick="Start()" id='input' value="Start"/>
Note: The following is the legacy answer. It will still work, but the newer Array.from()
method is now preferred. This could now be considered a polyfill to support pre-ES2015 targets.
Use .slice
to convert the attributes
property to Array
The attributes
property of DOM nodes is a NamedNodeMap
, which is an Array-like object.
An Array-like object is an object which has a length
property and whose property names are enumerated, but otherwise has its own methods and does not inherit from Array.prototype
The slice
method can be used to convert Array-like objects to a new Array.
var elem = document.getElementById('input'),
attrs = elem.attributes;
console.log('Array.prototype.slice.call(attrs)');
Array.prototype.slice.call(attrs).forEach(
function (cur) {
console.log(cur.name + ': ' + cur.value);
}
)
<input type='button' onClick="Start()" id='input' value="Start"/>