Sets the value of an attribute on the specified element. If the attribute already exists, the value is updated; otherwise a new attribute is added with the specified name and value.
To get the current value of an attribute, use
getAttribute()
; to remove an attribute, call
removeAttribute()
.
Element.setAttribute(name, value);
名称
DOMString
specifying the name of the attribute whose value is to be set. The attribute name is automatically converted to all lower-case when
setAttribute()
is called on an HTML element in an HTML document.
value
DOMString
containing the value to assign to the attribute. Any non-string value specified is converted automatically into a string.
Boolean attributes are considered to be
true
if they're present on the element at all, regardless of their actual
value
; as a rule, you should specify the empty string (
""
) 在
value
(some people use the attribute's name; this works but is non-standard). See the
范例
below for a practical demonstration.
Since the specified
value
gets converted into a string, specifying
null
doesn't necessarily do what you expect. Instead of removing the attribute or setting its value to be
null
, it instead sets the attribute's value to the string
"null"
. If you wish to remove an attribute, call
removeAttribute()
.
InvalidCharacterError
名称
contains one or more characters which are not valid in attribute names.
在以下范例中,
setAttribute()
is used to set attributes on a
<button>
.
<button>Hello World</button>
var b = document.querySelector("button");
b.setAttribute("name", "helloButton");
b.setAttribute("disabled", "");
This demonstrates two things:
setAttribute()
above shows changing the
名称
attribute's value to "helloButton". You can see this using your browser's page inspector (
Chrome
,
Edge
,
Firefox
,
Safari
).
被禁用
, you can specify any value. An empty string or the name of the attribute are recommended values. All that matters is that if the attribute is present at all,
regardless of its actual value
, its value is considered to be
true
. The absence of the attribute means its value is
false
. By setting the value of the
被禁用
attribute to the empty string (
""
), we are setting
被禁用
to
true
, which results in the button being disabled.
DOM methods dealing with element's attributes:
| Not namespace-aware, most commonly used methods | Namespace-aware variants (DOM Level 2) |
DOM Level 1 methods for dealing with
Attr
nodes directly (seldom used)
|
DOM Level 2 namespace-aware methods for dealing with
Attr
nodes directly (seldom used)
|
|---|---|---|---|
setAttribute
(DOM 1)
|
setAttributeNS
|
setAttributeNode
|
setAttributeNodeNS
|
getAttribute
(DOM 1)
|
getAttributeNS
|
getAttributeNode
|
getAttributeNodeNS
|
hasAttribute
(DOM 2)
|
hasAttributeNS
|
- | - |
removeAttribute
(DOM 1)
|
removeAttributeNS
|
removeAttributeNode
|
- |
| 规范 | 状态 | 注释 |
|---|---|---|
|
DOM
The definition of 'setAttribute()' in that specification. |
实时标准 |
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
setAttribute
|
Chrome 1 | Edge 12 | Firefox 1 |
IE
5
|
Opera 8 | Safari 3 | WebView Android 1 | Chrome Android 18 | Firefox Android 4 | Opera Android 10.1 | Safari iOS 1 | Samsung Internet Android 1.0 |
完整支持
见实现注意事项。
使用
setAttribute()
to modify certain attributes, most notably
value
in XUL, works inconsistently, as the attribute specifies the default value. To access or modify the current values, you should use the properties. For example, use
Element.value
而不是
Element.setAttribute()
.
元素
accessKey
属性
childElementCount
children
classList
className
clientHeight
clientLeft
clientTop
clientWidth
currentStyle
firstElementChild
id
innerHTML
lastElementChild
localName
名称
namespaceURI
nextElementSibling
onfullscreenchange
onfullscreenerror
openOrClosedShadowRoot
outerHTML
part
prefix
previousElementSibling
runtimeStyle
scrollHeight
scrollLeft
scrollLeftMax
scrollTop
scrollTopMax
scrollWidth
shadowRoot
slot
tabStop
tagName
after()
animate()
append()
attachShadow()
before()
closest()
computedStyleMap()
createShadowRoot()
getAnimations()
getAttribute()
getAttributeNames()
getAttributeNode()
getAttributeNodeNS()
getAttributeNS()
getBoundingClientRect()
getClientRects()
getElementsByClassName()
getElementsByTagName()
getElementsByTagNameNS()
hasAttribute()
hasAttributeNS()
hasAttributes()
hasPointerCapture()
insertAdjacentElement()
insertAdjacentHTML()
insertAdjacentText()
matches()
msZoomTo()
prepend()
querySelector()
querySelector()
querySelectorAll()
querySelectorAll()
releasePointerCapture()
remove()
removeAttribute()
removeAttributeNode()
removeAttributeNS()
replaceChildren()
replaceWith()
requestFullscreen()
requestPointerLock()
scroll()
scrollBy()
scrollIntoView()
scrollIntoViewIfNeeded()
scrollTo()
setAttribute()
setAttributeNode()
setAttributeNodeNS()
setAttributeNS()
setCapture()
setPointerCapture()
toggleAttribute()
afterscriptexecute
auxclick
blur
click
compositionend
compositionstart
compositionupdate
contextmenu
copy
cut
dblclick
DOMActivate
DOMMouseScroll
error
focus
focusin
focusout
fullscreenchange
fullscreenerror
gesturechange
gestureend
gesturestart
keydown
keypress
keyup
mousedown
mouseenter
mouseleave
mousemove
mouseout
mouseover
mouseup
mousewheel
MozMousePixelScroll
msContentZoom
MSGestureChange
MSGestureEnd
MSGestureHold
MSGestureStart
MSGestureTap
MSInertiaStart
MSManipulationStateChanged
overflow
paste
scroll
select
show
touchcancel
touchend
touchmove
touchstart
underflow
webkitmouseforcechanged
webkitmouseforcedown
webkitmouseforceup
webkitmouseforcewillbegin
wheel
AbortController
AbortSignal
AbstractRange
Attr
ByteString
CDATASection
CSSPrimitiveValue
CSSValue
CSSValueList
CharacterData
ChildNode
注释
CustomEvent
DOMConfiguration
DOMError
DOMErrorHandler
DOMException
DOMImplementation
DOMImplementationList
DOMImplementationRegistry
DOMImplementationSource
DOMLocator
DOMObject
DOMParser
DOMPoint
DOMPointInit
DOMPointReadOnly
DOMRect
DOMString
DOMTimeStamp
DOMTokenList
DOMUserData
Document
DocumentFragment
DocumentType
ElementTraversal
Entity
EntityReference
事件
EventTarget
HTMLCollection
MutationObserver
节点
NodeFilter
NodeIterator
NodeList
NonDocumentTypeChildNode
ProcessingInstruction
PromiseResolver
范围
StaticRange
文本
TextDecoder
TextEncoder
TimeRanges
TreeWalker
TypeInfo
USVString
UserDataHandler
XMLDocument