HTML DOM에서 input button 요소의 form 속성은 해당 입력 버튼을 감싸고 있는 <form> 요소에 대한 참조를 반환합니다. 이 속성을 활용하면 자바스크립트만으로 특정 버튼이 어떤 폼에 속해 있는지 쉽게 판별할 수 있습니다.
구문(Syntax)
form 속성의 기본 사용 구문은 다음과 같습니다.
object.form
반환값은 버튼을 포함하는 폼 객체이며, 버튼이 어떤 폼에도 속해 있지 않으면 null을 반환합니다.
예제(Example)
아래 예제는 두 개의 폼에 각각 버튼을 배치하고, 클릭된 버튼이 어느 폼에 속해 있는지 form 속성으로 판별하여 화면에 메시지를 표시합니다.
<!DOCTYPE html>
<html>
<head>
<title>HTML DOM form Property</title>
<style>
body{
text-align:center;
}
.btn{
display:block;
margin:1rem auto;
background-color:#db133a;
color:#fff;
border:1px solid #db133a;
padding:0.5rem;
border-radius:50px;
width:20%;
}
.show-message{
font-weight:bold;
font-size:1.4rem;
color:#ffc107;
}
</style>
</head>
<body>
<h1>form Property Example</h1>
<form id="form1">
<fieldset>
<legend>Form 1</legend>
<input type="button" class="btn" value="button 1">
<input type="button" class="btn" value="button 2">
</fieldset>
</form>
<form id="form2">
<fieldset>
<legend>Form 2</legend>
<input type="button" class="btn" value="button 1">
<input type="button" class="btn" value="button 2">
</fieldset>
</form>
<div class="show-message"></div>
<script>
var btnArr = document.querySelectorAll(".btn");
var showMessage = document.querySelector(".show-message");
btnArr.forEach((ele)=>{
ele.addEventListener("click",(e)=>{
showMessage.innerHTML="";
if(e.target.form.id === 'form1'){
showMessage.innerHTML="I'm from form 1";
} else {
showMessage.innerHTML="I'm from form 2";
}
})
});
</script>
</body>
</html>코드 동작 원리
위 예제의 핵심 로직은 다음과 같습니다.
document.querySelectorAll(".btn")으로 모든 버튼 요소를 선택합니다.- 각 버튼에 클릭 이벤트 리스너를 등록합니다.
- 버튼 클릭 시
e.target.form.id를 통해 해당 버튼이 속한 폼의 ID를 확인합니다. - ID가
form1이면 "I'm from form 1", 그렇지 않으면 "I'm from form 2"라는 메시지를 화면에 출력합니다.
출력(Output)
위 코드를 실행하면 다음과 같은 결과가 표시됩니다.

Form 1 영역의 button 1 / button 2를 클릭하면 다음과 같이 표시됩니다.

이번에는 Form 2 영역의 button 1 / button 2를 클릭해 보겠습니다.

이처럼 form 속성을 사용하면 별도의 데이터 속성이나 조건 분기 없이도, 클릭된 버튼이 어느 폼에 포함되어 있는지 즉시 확인할 수 있습니다. 여러 개의 유사한 폼을 하나의 스크립트로 처리할 때 특히 유용하게 활용됩니다.