getElementsByClassName
方法为
Document
interface
returns an array-like object of all child elements which have all of the given class name(s).
When called on the
document
object, the complete document is searched, including the root node. You may also call
getElementsByClassName()
on any element; it will return only elements which are descendants of the specified root element with the given class name(s).
var elements = document.getElementsByClassName(names); // or: var elements = rootElement.getElementsByClassName(names);
HTMLCollection
of found elements.
getElementsByClassName
can be called on any element, not only on the
document
. The element on which it is called will be used as the root of the search.
Get all elements that have a class of 'test':
document.getElementsByClassName('test')
Get all elements that have both the 'red' and 'test' classes:
document.getElementsByClassName('red test')
Get all elements that have a class of 'test', inside of an element that has the ID of 'main':
document.getElementById('main').getElementsByClassName('test')
Get the first element with a class of 'test', or
undefined
if there is no matching element:
document.getElementsByClassName('test')[0]
We can also use methods of Array.prototype on any
HTMLCollection
by passing the
HTMLCollection
as the method's
this
value. Here we'll find all div elements that have a class of 'test':
var testElements = document.getElementsByClassName('test');
var testDivs = Array.prototype.filter.call(testElements, function(testElement){
return testElement.nodeName === 'DIV';
});
This is the most commonly used method of operation.
<html>
<body>
<div id="parent-id">
<p>hello world 1</p>
<p class="test">hello world 2</p>
<p>hello world 3</p>
<p>hello world 4</p>
</div>
<script>
var parentDOM = document.getElementById("parent-id");
var test = parentDOM.getElementsByClassName("test"); // a list of matching elements, *not* the element itself
console.log(test); //HTMLCollection[1]
var testTarget = parentDOM.getElementsByClassName("test")[0]; // the first element, as we wanted
console.log(testTarget); //<p class="test">hello world 2</p>
</script>
</body>
</html>
document.getElementsByClassName
works very similarly to
document.querySelector
and
document.querySelectorAll
. Only elements with ALL of the classNames specified are selected.
<span class="orange fruit">Orange Fruit</span> <span class="orange juice">Orange Juice</span> <span class="apple juice">Apple Juice</span> <span class="foo bar">Something Random</span> <textarea id="resultArea" style="width:98%;height:7em"></textarea>
// getElementsByClassName only selects elements that have both given classes
var allOrangeJuiceByClass = document.getElementsByClassName('orange juice');
var result = "document.getElementsByClassName('orange juice')";
for (var i=0, len=allOrangeJuiceByClass.length|0; i<len; i=i+1|0) {
result += "\n " + allOrangeJuiceByClass[i].textContent;
}
// querySelector only selects full complete matches
var allOrangeJuiceQuery = document.querySelectorAll('.orange.juice');
result += "\n\ndocument.querySelectorAll('.orange.juice')";
for (var i=0, len=allOrangeJuiceQuery.length|0; i<len; i=i+1|0) {
result += "\n " + allOrangeJuiceQuery[i].textContent;
}
document.getElementById("resultArea").value = result;
| 规范 | 状态 | 注释 |
|---|---|---|
|
DOM
The definition of 'document.getElementsByClassName' in that specification. |
实时标准 |
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
getElementsByClassName
|
Chrome 1 | Edge 12 | Firefox 4 | IE 9 | Opera 9.5 | Safari 3.1 | WebView Android 1 | Chrome Android 18 | Firefox Android 4 | Opera Android 10.1 | Safari iOS 2 | Samsung Internet Android 1.0 |
完整支持
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