Computer >> 컴퓨터 >  >> 프로그래밍 >> HTML

HTML DOM className 속성 완벽 정리 – 문법부터 실전 예제까지

HTML DOM의 className 속성은 HTML 요소에 CSS 클래스를 할당하거나 조회할 때 사용됩니다. 이 속성은 요소의 class 속성 값을 설정하거나 반환하는 역할을 하며, 만약 요소에 연결된 클래스가 없다면 빈 문자열("")이 반환됩니다. 또한 className 속성을 활용하면 요소에 포함된 기존 클래스 이름을 자유롭게 변경할 수 있습니다.

문법(Syntax)

className 속성의 기본적인 사용 방법은 다음과 같습니다.

className 설정하기

HTMLElementObject.className = class;

여기서 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>

실행 결과

위 코드를 실행하면 다음과 같은 화면이 출력됩니다.

HTML DOM className 속성 완벽 정리 – 문법부터 실전 예제까지

GET CLASS 버튼을 클릭하면 아래와 같이 결과가 표시됩니다.

HTML DOM className 속성 완벽 정리 – 문법부터 실전 예제까지

예제 코드 상세 분석

위 예제에서 수행된 과정을 단계별로 살펴보겠습니다.

먼저 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() 메서드로 <div> 요소를 가져온 뒤, className 속성을 통해 해당 요소의 모든 클래스 이름을 읽어 변수 x에 저장합니다. 이후 저장된 클래스 이름들은 id가 "Sample"인 단락(<p>)에 출력됩니다.

function getClassName() {
    var x = document.getElementById("myDIV").className;
    document.getElementById("Sample").innerHTML ="The classNames with the div element are "+x;
}

이처럼 className 속성을 활용하면 자바스크립트만으로 요소의 클래스 정보를 손쉽게 확인하고 수정할 수 있어, 동적인 스타일 변경이나 UI 인터랙션 구현에 매우 유용하게 사용됩니다.