A lot of DOM attributes can be accessed via properties. For example, the class
attribute can be accessed via the className
property. The answers in the following thread suggest that you should always use properties over attributes wherever possible, for performance reasons.
When to use setAttribute vs .attribute= in JavaScript?
So, I created a helper function which sets properties.
const setAttribute = (node, name, value) => {
node[name] = value;
};
However, this doesn't work for non-standard attributes such as aria-label
which don't have corresponding properties. So, given a node, a name, and a value, how do I determine whether the name is a property name or an attribute name? I'm trying to do something as follows.
const setAttribute = (node, name, value) => {
if (isPropertyName(node, name, value)) {
node[name] = value;
} else {
node.setAttribute(name, value);
}
};
Is it possible to implement the isPropertyName
function? If so, how? Assume that the attribute wasn't previously created. Hence, node[name]
returns undefined
and node.hasAttribute(name)
returns null
.
If there's no way to implement the isPropertyName
function, then should I always use setAttribute
instead? I need to handle this for the general case. For specific cases, I could create a map from attribute names to property names. Is there a better way to do this?