We can get all attributes of an element with JavaScript by using the node.attributes
property.
For instance, if we have the following HTML:
<div style='color: red' class="myDiv" id="myDiv">
</div>
Then we can write:
const node = document.querySelector('div')
const attributeNodeArray = [...node.attributes];
const attrs = attributeNodeArray.reduce((attrs, attribute) => {
attrs[attribute.name] = attribute.value;
return attrs;
}, {});
console.log(attrs)
to get all the attributes of the div into an object.
We spread the node.attributes
object into an array.
Then we call reduce
on the array to add all the attribute.name
property with attribute.value
into the attrs
object with the callback
We return attrs
in the callback.
In the 2nd argument, we pass in an empty object to set that as the value of attrs
.
Therefore, attrs
is:
{style: "color: red", class: "myDiv", id: "myDiv"}
Get All Attributes of an Element Using jQuery
We can use the jQuery each
method to loop through all the attributes and the attribute name as the property name and the attribute value as the value of the property.
To do this, we write:
const [node] = $('div')
const attrs = {}
$.each(node.attributes, (index, attribute) => {
attrs[attribute.name] = attribute.value;
});
console.log(attrs)
We destructure the div returned from the $
function.
Then we create the empty attrs
object.
Next, we call each
with node.attrbiutes
to loop through all the attributes.
And in the callback, we populate attrs
with attribute.name
as the property name and attribute.value
as the property value.
And we get the same result as before.