JS DOM: Element Attribute Methods

By Xah Lee. Date: . Last updated: .

Methods on Element Attributes

get / set attributes

node.getAttribute(attr)
node.setAttribute(attr, val)

check existance

node.hasAttribute(attr)

Return true or false.

This is especially useful for “boolean attributes” that do not have values. e.g. the controls in HTML: Video Tag

remove

node.removeAttribute(attr)

list attributes

node.attributes

Get all attributes. Return a Live Object of NamedNodeMap object.

Dedicated Methods for Class Attribute

Properties for Standard HTML Attributes

The following works with standard HTML attributes only, such as id, class, name, etc.

🛑 warning: Note, HTML Element properties may not work with generic XML attributes, e.g. SVG's stroke. [see SVG: Specifying Styles]

HtmlElement.AttributeName

Return element's attribute's value, or undefined if it doesn't exist.

HtmlElement.AttributeName = value
  • Set a element's attribute.
  • Return value.
  • If AttributeName is not a standard html attribute, it's not added.

HTML style attribute