Document
方法
getElementById()
返回
元素
object representing the element whose
id
property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.
If you need to get access to an element which doesn't have an ID, you can use
querySelector()
to find the element using any
选择器
.
var element = document.getElementById(id);
id
The ID of the element to locate. The ID is case-sensitive string which is unique within the document; only one element may have any given ID.
元素
object describing the DOM element object matching the specified ID, or
null
if no matching element was found in the document.
<html>
<head>
<title>getElementById example</title>
</head>
<body>
<p id="para">Some text here</p>
<button onclick="changeColor('blue');">blue</button>
<button onclick="changeColor('red');">red</button>
</body>
</html>
function changeColor(newColor) {
var elem = document.getElementById('para');
elem.style.color = newColor;
}
The capitalization of
"Id"
in the name of this method
must
be correct for the code to function;
getElementByID()
is
not
valid and will not work, however natural it may seem.
Unlike some other element-lookup methods such as
Document.querySelector()
and
Document.querySelectorAll()
,
getElementById()
is only available as a method of the global
document
object, and
not
available as a method on all element objects in the DOM. Because ID values must be unique throughout the entire document, there is no need for "local" versions of the function.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="parent-id">
<p>hello word1</p>
<p id="test1">hello word2</p>
<p>hello word3</p>
<p>hello word4</p>
</div>
<script>
var parentDOM = document.getElementById('parent-id');
var test1 = parentDOM.getElementById('test1');
//throw error
//Uncaught TypeError: parentDOM.getElementById is not a function
</script>
</body>
</html>
If there is no element with the given
id
,此函数返回
null
。注意,
id
parameter is case-sensitive, so
document.getElementById("
M
ain")
将返回
null
instead of the element
<div id="
m
ain">
because "M" and "m" are different for the purposes of this method.
Elements not in the document
are not searched by
getElementById()
. When creating an element and assigning it an ID, you have to insert the element into the document tree with
Node.insertBefore()
or a similar method before you can access it with
getElementById()
:
var element = document.createElement('div');
element.id = 'testqq';
var el = document.getElementById('testqq'); // el will be null!
Non-HTML documents
. The DOM implementation must have information that says which attributes are of type ID. Attributes with the name "id" are not of type ID unless so defined in the document's DTD. The
id
attribute is defined to be of ID type in the common cases of
XHTML
,
XUL
, and other. Implementations that do not know whether attributes are of type ID or not are expected to return
null
.
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
getElementById
|
Chrome 1 | Edge 12 | Firefox 1 | IE 5.5 | Opera 7 | Safari 1 | WebView Android 1 | Chrome Android 18 | Firefox Android 4 | Opera Android 10.1 | Safari iOS 1 | Samsung Internet Android 1.0 |
完整支持
Document
reference for other methods and properties you can use to get references to elements in the document.
Document.querySelector()
for selectors via queries like
'div.myclass'
getElementById()
to obtain 'xml:id' in XML documents (such as returned by Ajax calls)
Document
alinkColor
all
anchors
applets
bgColor
body
characterSet
childElementCount
children
compatMode
contentType
currentScript
defaultView
designMode
dir
doctype
documentElement
documentURI
documentURIObject
domain
domConfig
嵌入
fgColor
firstElementChild
forms
fullscreen
fullscreenEnabled
head
height
hidden
图像
实现
lastElementChild
lastModified
lastStyleSheetSet
linkColor
链接
location
mozSyntheticDocument
onabort
onafterscriptexecute
onanimationcancel
onanimationend
onanimationiteration
onauxclick
onbeforescriptexecute
onblur
oncancel
oncanplay
oncanplaythrough
onchange
onclick
onclose
oncontextmenu
oncuechange
ondblclick
ondurationchange
onended
onerror
onfocus
onformdata
onfullscreenchange
onfullscreenerror
ongotpointercapture
oninput
oninvalid
onkeydown
onkeypress
onkeyup
onload
onloadeddata
onloadedmetadata
onloadend
onloadstart
onlostpointercapture
onmousedown
onmouseenter
onmouseleave
onmousemove
onmouseout
onmouseover
onmouseup
onoffline
ononline
onpause
onplay
onplaying
onpointercancel
onpointerdown
onpointerenter
onpointerleave
onpointermove
onpointerout
onpointerover
onpointerup
onreset
onresize
onscroll
onselect
onselectionchange
onselectstart
onsubmit
ontouchcancel
ontouchstart
ontransitioncancel
ontransitionend
onvisibilitychange
onwheel
origin
plugins
popupNode
preferredStyleSheetSet
readyState
referrer
rootElement
脚本
scrollingElement
selectedStyleSheetSet
styleSheetSets
timeline
title
tooltipNode
URL
visibilityState
vlinkColor
width
xmlEncoding
xmlVersion
adoptNode()
append()
caretRangeFromPoint()
clear()
close()
createAttribute()
createCDATASection()
createComment()
createDocumentFragment()
createElement()
createElementNS()
createEntityReference()
createEvent()
createExpression()
createExpression()
createNodeIterator()
createNSResolver()
createNSResolver()
createProcessingInstruction()
createRange()
createTextNode()
createTouch()
createTouchList()
createTreeWalker()
enableStyleSheetsForSet()
evaluate()
evaluate()
execCommand()
exitFullscreen()
exitPointerLock()
getAnimations()
getBoxObjectFor()
getElementById()
getElementsByClassName()
getElementsByName()
getElementsByTagName()
getElementsByTagNameNS()
hasFocus()
hasStorageAccess()
importNode()
mozSetImageElement()
open()
prepend()
queryCommandEnabled()
queryCommandSupported()
querySelector()
querySelector()
querySelectorAll()
querySelectorAll()
registerElement()
releaseCapture()
replaceChildren()
requestStorageAccess()
write()
writeln()
animationcancel
animationend
animationiteration
animationstart
copy
cut
DOMContentLoaded
drag
dragend
dragenter
dragexit
dragleave
dragover
dragstart
drop
fullscreenchange
fullscreenerror
gotpointercapture
keydown
keypress
keyup
lostpointercapture
paste
pointercancel
pointerdown
pointerenter
pointerleave
pointerlockchange
pointerlockerror
pointermove
pointerout
pointerover
pointerup
readystatechange
scroll
selectionchange
selectstart
touchcancel
touchend
touchmove
touchstart
transitioncancel
transitionend
transitionrun
transitionstart
visibilitychange
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
DocumentFragment
DocumentType
元素
ElementTraversal
Entity
EntityReference
事件
EventTarget
HTMLCollection
MutationObserver
节点
NodeFilter
NodeIterator
NodeList
NonDocumentTypeChildNode
ProcessingInstruction
PromiseResolver
范围
StaticRange
文本
TextDecoder
TextEncoder
TimeRanges
TreeWalker
TypeInfo
USVString
UserDataHandler
XMLDocument