JS: 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: 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
- JS: What is Node, Node Type, Element
- JS: Get Element by ID, Name, Class etc
- JS: Get Element Parent, Child, Sibling
- DOM: NodeList vs HTMLCollection
- JS: Iterate HTMLCollection
- JS: Element Attribute Methods
- JS: List, Add, Remove Class Attribute
- JS: Create Element, Clone
- JS: Insert, Remove, Replace Element
- JS: Change Element Content
- JS: Add, Remove Event Handler