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

HTML DOM Legend form 속성 완벽 정리 – 사용법과 예제 코드

HTML DOM의 Legend form 속성은 <legend> 태그를 감싸고 있는 폼(form) 요소에 대한 참조를 반환하는 속성입니다. 이 속성을 활용하면 자바스크립트를 통해 범례가 속한 폼의 정보에 쉽게 접근할 수 있습니다.

문법(Syntax)

Legend form 속성의 기본 문법은 다음과 같습니다.

form 객체에 대한 참조 반환하기

legendObject.form

예제(Example)

다음은 Legend form 속성을 실제로 활용한 예제 코드입니다. 버튼을 클릭하면 범례가 포함된 폼의 id 값을 화면에 출력합니다.

<!DOCTYPE html>
<html>
<head>
<title>Legend form</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 id="Mid-Term">
<fieldset>
<legend id="legendForm">Legend-form</legend>
<label for="WeekSelect">시험 주간:
<input type="week" value="2019-W36">
</label>
<input type="button" onclick="showExamination()" value="이번 주 시험은 무엇인가요?">
<div id="divDisplay"></div>
</fieldset>
</form>
<script>
    var divDisplay = document.getElementById("divDisplay");
    var legendForm = document.getElementById("legendForm");
    function showExamination() {
        divDisplay.textContent = '시험: '+legendForm.form.id;
    }
</script>
</body>
</html>

출력 결과(Output)

위 코드를 실행하면 다음과 같은 결과를 확인할 수 있습니다.

'이번 주 시험은 무엇인가요?' 버튼을 클릭하기 전 화면 −

HTML DOM Legend form 속성 완벽 정리 – 사용법과 예제 코드

'이번 주 시험은 무엇인가요?' 버튼을 클릭한 후 화면 −

HTML DOM Legend form 속성 완벽 정리 – 사용법과 예제 코드

버튼을 클릭하면 showExamination() 함수가 호출되고, legendForm.form.id를 통해 범례(legend)가 속한 폼의 id인 'Mid-Term' 값이 div 영역에 표시됩니다. 이처럼 Legend form 속성은 DOM 트리에서 특정 요소가 어떤 폼에 속해 있는지 확인할 때 유용하게 사용됩니다.