Working with element attributes in JavaScript is a common task when working with the DOM. In this note, we’ll look at how to get, set, and remove attributes from HTML elements using JavaScript.

Getting Attributes

This function gets the attributes of an element and returns them as an object.

const getAttributes = (
  element: Element,
  namespace: string | null = null
) => {
  var attributesNames = element.getAttributeNames()
  const attrs: Record<string, any> = {}

  for (const attributeName in attributesNames) {
    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, attributeName)
    } 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 = []

  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(' ')
}