HTML DOM에서 Label 객체는 HTML의 <label> 요소를 나타냅니다. <label> 요소는 폼 컨트롤에 대한 설명 텍스트를 제공하는 역할을 하며, 자바스크립트를 통해 동적으로 생성하거나 조작할 수 있습니다.
문법(Syntax)
<label> 요소를 새로 생성하는 기본 문법은 다음과 같습니다.
var labelObject = document.createElement("LABEL");
주요 속성(Properties)
Label 객체에서 사용할 수 있는 주요 속성은 다음과 같습니다.
| 속성 | 설명 |
|---|---|
| control | 레이블에 연결된 컨트롤(입력 요소)을 반환합니다. |
| form | 해당 레이블을 포함하고 있는 상위 폼(form)에 대한 참조를 반환합니다. |
| htmlFor | 레이블의 for 속성 값을 가져오거나 설정합니다. |
예제: htmlFor 속성 활용하기
다음 예제는 htmlFor 속성을 사용하여 버튼 클릭 시 레이블의 for 속성 값을 동적으로 변경하는 방법을 보여줍니다.
<!DOCTYPE html>
<html>
<head>
<title>Label htmlFor</title>
<style>
form {
width:70%;
margin: 0 auto;
text-align: center;
}
* {
padding: 2px;
margin:5px;
}
input[type="button"] {
border-radius: 10px;
}
</style>
</head>
<body>
<form>
<fieldset>
<legend>Label-htmlFor</legend>
<label id="CurrentEditor" for="editorTwo">현재 편집기:</label><br>
<input type="text" id="editorOne" placeholder="editorOne">
<input type="text" id="editorTwo" placeholder="editorTwo">
<input type="button" onclick="getEventData()" value="편집기 변경">
<div id="divDisplay">레이블의 for 속성이 editor two로 설정되어 있습니다</div>
</fieldset>
</form>
<script>
var divDisplay = document.getElementById("divDisplay");
var labelSelect = document.getElementById("CurrentEditor");
function getEventData() {
if(labelSelect.htmlFor === 'editorTwo'){
divDisplay.textContent = '레이블의 for 속성이 editor one으로 변경되었습니다';
labelSelect.htmlFor = 'editorOne';
}
}
</script>
</body>
</html>
실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
'편집기 변경' 버튼을 클릭하기 전 −

'편집기 변경' 버튼을 클릭한 후 −

버튼을 클릭하면 스크립트가 실행되어 레이블의 for 속성 값이 editorTwo에서 editorOne으로 변경되며, 하단 표시 영역에 변경 결과가 텍스트로 나타납니다. 이처럼 htmlFor 속성을 활용하면 레이블과 입력 요소 간의 연결 관계를 자바스크립트로 자유롭게 제어할 수 있습니다.