This article is based on the JavaScript standard tutorial - Ruan Yifeng finishing notes
Element.attributes property
The properties of the element object attributes
return an array-like dynamic object of which all property node objects of the element are members.
We can reference property nodes in the following three ways:
// <body id="myBody">
document.body.attributes[0]
document.body.attributes.id
document.body.attributes['ID']
//注意它们返回的属性节点对象, 不是属性值
For attribute nodes, we can get attribute names and attribute values through name
and attributes, or we can use , and attributes, their return values are all stringsvalue
nodeName
nodeValue
// <body id="myBody">
var body = document.body.attributes[0]
body.attributes[0].name //"id"
body.attributes[0].nodeName//"id"
body.attributes[0].value//"myBody"
body.attributes[0].nodeValue//"myBody"
standard attributes of elements
html
The standard properties of an element automatically become properties of the element node object. These properties are all writable. But these attributes cannot be deleted, i.e. have delete
no effect on them
Standard Methods for Attribute Manipulation
Element nodes have four methods to manipulate properties
getAttribute(name)
: Getname
the attribute value with the attribute name, if it does not exist, returnnull
setAttribute(name, value)
: Add a new attribute, setname
the value of thevalue
attribute, if the attribute already exists, edit the existing attribute.hasAttribute(name)
: Determine whether the element has anname
attribute, return if there is, returntrue
if notfalse
removeAttribute(name)
: delete the propertyname
with the property name
dataset property
For custom attributes, we can use the data-prefix method to represent
<div id="mydiv" data-foo="bar">
Note: data-
The following attribute names are limited and can only contain letters, numbers, hyphens ( -
), dots ( .
), colons ( :
) and underscores ( _
). Also, property names should not use capital letters, for example, there cannot be A
such property names, but should be written .Z
data-helloWorld
data-hello-world
Although we can also getAttribute()
get custom attributes in this way, but this will make the html
element non-standard.
We can use dataset
properties to read
var div = document.getElementById('mydiv');
div.dataset.foo // bar
div.dataset.foo = 'baz'
When converting to dataset
a key name, if the conjunction line is followed by a lowercase letter, the conjunction line will be removed, the lowercase letter will be converted to an uppercase letter, and other characters will remain unchanged. Conversely, dataset
when the key name is converted to an attribute name, all uppercase letters will be converted to a conjunction line + the lowercase form of the letter, and other characters remain unchanged. For example, dataset.helloWorld
it will turn into data-hello-world
.
Deleting custom attributes can directly use the delete
command