I want to put all attributes in a Html element into an array: like i have a jQuery Object, whichs html looks like this:
In javascript:
var attributes;
var spans = document.getElementsByTagName("span");
for(var s in spans){
if (spans[s].getAttribute('name') === 'test') {
attributes = spans[s].attributes;
break;
}
}
To access the attributes names and values:
attributes[0].nodeName
attributes[0].nodeValue
This approach works well if you need to get all the attributes with name and value in objects returned in an array.
Example output:
[
{
name: 'message',
value: 'test2'
}
...
]
function getElementAttrs(el) {
return [].slice.call(el.attributes).map((attr) => {
return {
name: attr.name,
value: attr.value
}
});
}
var allAttrs = getElementAttrs(document.querySelector('span'));
console.log(allAttrs);
<span name="test" message="test2"></span>
If you want only an array of attribute names for that element, you can just map the results:
var onlyAttrNames = allAttrs.map(attr => attr.name);
console.log(onlyAttrNames); // ["name", "message"]
Much more concise ways to do it:
var element = document.querySelector(/* … */);
[].slice.call(element.attributes).map(function (attr) { return attr.nodeName; });
[...document.querySelector(/* … */).attributes].map(attr => attr.nodeName);
console.log(
[...document.querySelector('img').attributes].map(attr => attr.nodeName)
);
/* Output console formatting */
.as-console-wrapper { position: absolute; top: 0; }
<img src="…" alt="…" height="…" width="…"/>
Every answer here is missing the simplest solution using the getAttributeNames element method!
It retrieves the names of all the element's current attributes as a regular Array, that you can then reduce to a nice object of keys/values.
const getAllAttributes = el => el
.getAttributeNames()
.reduce((obj, name) => ({
...obj,
[name]: el.getAttribute(name)
}), {})
console.log(getAllAttributes(document.querySelector('div')))
<div title="hello" className="foo" data-foo="bar"></div>
Because in IE7 elem.attributes lists all possible attributes, not only the present ones, we have to test the attribute value. This plugin works in all major browsers:
(function($) {
$.fn.getAttributes = function () {
var elem = this,
attr = {};
if(elem && elem.length) $.each(elem.get(0).attributes, function(v,n) {
n = n.nodeName||n.name;
v = elem.attr(n); // relay on $.fn.attr, it makes some filtering and checks
if(v != undefined && v !== false) attr[n] = v
})
return attr
}
})(jQuery);
Usage:
var attribs = $('#some_id').getAttributes();
Element.prototype.getA = function (a) {
if (a) {
return this.getAttribute(a);
} else {
var o = {};
for(let a of this.attributes){
o[a.name]=a.value;
}
return o;
}
}
having <div id="mydiv" a='1' b='2'>...</div>
can use
mydiv.getA() // {id:"mydiv",a:'1',b:'2'}