JS DOM: Element Attribute Methods

By Xah Lee. Date: . Last updated: .

Methods on Element Attributes

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

node.getAttribute(attr)
node.setAttribute(attr, val)
node.removeAttribute(attr)
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.

Properties for CSS Style Attribute

node.style.cssProperty

Return the property value, or undefined if it doesn't exist.

node.style.cssProperty=value
  • Set CSS property.
  • Return value.
  • If the property is not a standard CSS property, it's not added.

example JS DOM: Change CSS

Basic DOM Element Methods