현재 번역은 완벽하지 않습니다. 한국어로 문서 번역에 동참해주세요.

Returns an array-like object of all child elements which have all of the given class names. 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 names.

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 list of class names to match; 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.

예시

'Test'라고 이름 지어진 모든 클래스 엘리먼트를 가져옵니다.

document.getElementsByClassName('test');

'Red'와 'Test'라고 이름 지어진 모든 클래스 엘리먼트를 가져옵니다.

document.getElementsByClassName('red test');

ID 엘리먼트가 'main'인 엘리먼트 안의 'Test'라고 이름 지어진 모든 클래스 엘리먼트를 가져옵니다.

document.getElementById('main').getElementsByClassName('test');

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 class is test elements

This is the most commonly used method of operation

<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <div id="parent-id">
        <p>hello word1</p>
        <p class="test">hello word2</p>
        <p >hello word3</p>
        <p>hello word4</p>
    </div>
    <script>
        var parentDOM = document.getElementById("parent-id");
        
        var test=parentDOM.getElementsByClassName("test");//test is not target element
        console.log(test);//HTMLCollection[1]

        var testTarget=parentDOM.getElementsByClassName("test")[0];//hear , this element is target
        console.log(testTarget);//<p class="test">hello word2</p>
    </script>
</body>
</html>

브라우저 안정성

 

Feature 크롬 마이크로소프트 엣지 Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) 3.0 9.0 (Yes) (Yes)
  
Feature 안드로이드 Edge Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support ? (Yes) ? ? ? ?

Specification

문서 태그 및 공헌자

 이 페이지의 공헌자: Dear-Min
 최종 변경: Dear-Min,