Document.getElementsByClassName() - Web APIs 编辑

The getElementsByClassName method of 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).

Warning: This is a live HTMLCollection. Changes in the DOM will reflect in the array as the changes occur. If an element selected by this array no longer qualifies for the selector, it will automatically be removed. Be aware of this for iteration purposes.

Syntax

var elements = document.getElementsByClassName(names); // or:
var elements = rootElement.getElementsByClassName(names);
  • elements is a live HTMLCollection of found elements.
  • names is a string representing the class name(s) to match; multiple class names are separated by whitespace
  • 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.

Examples

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';
});

Get the first element whose class is 'test'

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>

Multiple Classes Example

document.getElementsByClassName works very similarly to document.querySelector and document.querySelectorAll. Only elements with ALL of the classNames specified are selected.

HTML

<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>

JavaScript

// 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;

Result

Specifications

SpecificationStatusComment
DOM
The definition of 'document.getElementsByClassName' in that specification.
Living Standard

Browser compatibility

BCD tables only load in the browser

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:84 次

字数:7310

最后编辑:8年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文