Three utility functions for reading and writing HTML element attributes, with namespace support.
Getting Attributes
This function gets the attributes of an element and returns them as an object.
const getAttributes = (
element: Element,
namespace: string | null = null,
) => {
const attributeNames = element.getAttributeNames()
const attrs: Record<string, string | null> = {}
for (const attributeName of attributeNames) {
attrs[attributeName] = element.getAttributeNS(namespace, attributeName)
}
return attrs
}Setting Attributes
This function sets the attributes of an element using the provided object. It removes attributes that are undefined or null.
const setAttributes = (
element: Element,
attributes: Record<string, string | number | boolean | null | undefined>,
namespace: string | null = null,
) => {
for (const [name, value] of Object.entries(attributes)) {
if (typeof value === 'undefined' || value === null) {
element.removeAttributeNS(namespace, name)
} else {
element.setAttributeNS(namespace, name, value.toString())
}
}
}Stringifying Attributes
Sometimes you may want to convert an object of attributes into a string that can be used in HTML. This function does that.
function stringifyAttributes(attributes: Record<string, string | number | undefined | null | boolean>): string {
const result: string[] = []
for (const [key, value] of Object.entries(attributes)) {
if (
value !== undefined &&
value !== null &&
!Number.isNaN(value) &&
value !== Number.POSITIVE_INFINITY &&
value !== Number.NEGATIVE_INFINITY
) {
result.push(`${key}="${value.toString()}"`)
}
}
return result.join(' ')
}