JS: 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)
〔see Get Element's Attribute Value
node.setAttribute(attr, val)
〔see Set Element's Attribute Value
node.removeAttribute(attr)
〔see Remove Element's Attribute Value
node.attributes
Get all attributes. Return a Live Object of NamedNodeMap object.

Class Attribute Methods

For the HTML: Class Attribute , there is more useful methods.

see List Add Remove Class

HTML Attribute Properties

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

🛑 WARNING: they do not work with generic XML attributes.

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.

“style” Attribute

For the style attribute, you can use HTML Element properties.

Note, HTML Element properties may not work with XML, e.g. SVG's stroke. 〔see SVG: Specifying Styles

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.

see Change CSS

Basic DOM Element Methods