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 Attribute

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.CssAttribute
Return the attribute value, or undefined if it doesn't exist.
node.style.CssAttribute=value
Set css attribute. Return value. If attribute is not a standard css attribute, it's not added.

see Change CSS

BUY ΣJS JavaScript in Depth

Basic DOM Element Methods