HTML DOM className 속성은 HTML 요소에 CSS 클래스를 할당하는 데 사용됩니다. className 속성은 요소의 클래스 이름 속성 값을 설정하거나 반환하는 데 사용됩니다. HTML 요소와 연결된 클래스가 없으면 빈 문자열이 반환됩니다. 이 속성을 사용하여 요소에 포함된 클래스 이름을 변경할 수 있습니다. -
구문
다음은 −
의 구문입니다.className 속성 설정 -
HTMLElementObject.className = class;
여기에서 클래스 값은 요소의 클래스 이름을 지정하는 데 사용됩니다. 요소는 공백으로 구분하여 연결된 여러 클래스를 가질 수 있습니다.
예시
HTML DOM className 속성의 예를 살펴보겠습니다 -
<!DOCTYPE html>
<html>
<head>
<style>
.firstDiv {
width: 300px;
height: 100px;
background-color:lightgreen;
}
.secondDiv{
color: red;
border:solid 1px blue;
margin-bottom:9px;
}
</style>
</head>
<body>
<p>Click the below button to display the class attribute value of the div </p>
<div id="myDIV" class="firstDiv secondDiv">
This is a sample div element.
</div>
<button onclick="getClassName()">GET CLASS</button>
<p id="Sample"></p>
<script>
function getClassName() {
var x = document.getElementById("myDIV").className;
document.getElementById("Sample").innerHTML ="The classNames with the div element
are "+x;
}
</script>
</body>
</html> 출력
이것은 다음과 같은 출력을 생성합니다 -

GET CLASS 버튼 클릭 시 -

위의 예에서 -
우리는 ID가 "myDIV"인 div를 생성했으며 여기에는 일부 텍스트가 포함되어 있습니다. −
<div id="myDIV" class="firstDiv secondDiv"> This is a sample div element. </div>
그런 다음 클릭 시 getClassName() 메서드를 실행하는 GET CLASS 버튼을 만들었습니다. −
<button onclick="getClassName()">GET CLASS</button>
getClassName() 메서드는 getElementById() 메서드를 사용하여
요소를 가져오고
요소의 className 속성을 사용하여 모든 클래스 이름을 가져와 변수 x에 할당합니다. 그러면 클래스 이름이 id가 "Sample"인 단락에 표시됩니다 -
function getClassName() {
var x = document.getElementById("myDIV").className;
document.getElementById("Sample").innerHTML ="The classNames with the div element are "+x;
}