元素
方法
getElementsByClassName()
returns a live
HTMLCollection
which contains every descendant element which has the specified class name or names.
方法
getElementsByClassName()
在
Document
interface works essentially the same way, except it acts on the entire document, starting at the document root.
var elements = element.getElementsByClassName(names);
名称
DOMString
containing one or more class names to match on, separated by whitespace.
HTMLCollection
providing a live-updating list of every element which is a member of every class in
名称
.
As always, the returned collection is
live
, meaning that it always reflects the current state of the DOM tree rooted at the element on which the function was called. As new elements that match
名称
are added to the subtree, they immediately appear in the collection. Similarly, if an existing element that doesn't match
名称
has its set of classes adjusted so that it matches, it immediately appears in the collection.
The opposite is also true; as elements no longer match the set of names, they are immediately removed from the collection.
在 quirks mode , the class names are compared in a case-insensitive fashion. Otherwise, they're case sensitive.
To look for elements that include among their classes a single specified class, we just provide that class name when calling
getElementsByClassName()
:
element.getElementsByClassName('test');
This example finds all elements that have a class of
test
, which are also a descendant of the element that has the
id
of
main
:
document.getElementById('main').getElementsByClassName('test');
To find elements whose class lists include both the
red
and
test
类:
element.getElementsByClassName('red test');
You can use either the
item()
method on the returned
HTMLCollection
or standard array syntax to examine individual elements in the collection. However
the following code will not work
as one might expect because
"matches"
will change as soon as any
"colorbox"
class is removed.
var matches = element.getElementsByClassName('colorbox');
for (var i=0; i<matches.length; i++) {
matches[i].classList.remove('colorbox');
matches.item(i).classList.add('hueframe');
}
Instead, use another method, such as:
var matches = element.getElementsByClassName('colorbox');
while (matches.length > 0) {
matches.item(0).classList.add('hueframe');
matches[0].classList.remove('colorbox');
}
This code finds descendant elements with the
"colorbox"
class, adds the class
"hueframe"
, by calling
item(0),
then removes
"colorbox"
(using array notation). Another element (if any are left) will then become
item(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';
});
| 规范 | 状态 | 注释 |
|---|---|---|
|
DOM
The definition of 'Element.getElementsByClassName()' in that specification. |
实时标准 | 初始定义 |
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
getElementsByClassName
|
Chrome 1 |
Edge
18
|
Firefox
3
|
IE
9
|
Opera 9.5 | Safari 6 | WebView Android 1 | Chrome Android 18 | Firefox Android 4 | Opera Android 10.1 | Safari iOS 6 | Samsung Internet Android 1.0 |
完整支持
见实现注意事项。
元素
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