JavaScript: Element Attribute Methods
Methods on Element Attributes
-
node.hasAttribute(attr)
-
Return
true
orfalse
. This is especially useful for “boolean attributes” that do not have values. e.g. thecontrols
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.
HTML Attribute Properties
The following works with standard HTML attributes only, such as id
, class
, name
, etc.
(WARNING: 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, example: 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