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

HTML DOM 입력 버튼(Input Button) 객체 완벽 정리

HTML DOM Input Button 객체는 type 속성이 "button"으로 설정된 HTML <input> 요소를 JavaScript에서 다룰 수 있도록 해주는 객체입니다. 이 객체를 활용하면 버튼을 동적으로 생성하고, 속성을 읽거나 수정하는 등의 작업을 스크립트로 제어할 수 있습니다.

입력 버튼 객체 생성 방법

JavaScript에서 Input Button 객체를 생성하는 기본 문법은 다음과 같습니다.

var newButton = document.createElement("INPUT");
newButton.setAttribute("type", "value");

여기서 value 자리에는 "button", "submit", "reset" 중 하나를 지정할 수 있습니다.

입력 버튼 객체의 주요 속성

Input Button 객체가 제공하는 대표적인 속성은 아래와 같습니다.

속성설명
autofocus입력 버튼의 autofocus 속성 값을 반환하며, 값을 변경할 수도 있습니다.
defaultValue입력 버튼에 설정된 기본값(default value)을 반환하고 수정할 수 있습니다.
disabled입력 버튼의 disabled 속성 값을 반환하며, 버튼의 비활성화 여부를 제어할 수 있습니다.
form해당 입력 버튼을 감싸고 있는 폼(form) 요소의 참조를 반환합니다.
name입력 버튼의 name 속성 값을 반환하고 변경할 수 있습니다.
type버튼의 유형을 반환합니다. 즉, "button", "submit", "reset" 중 어떤 타입인지 확인할 수 있습니다.
value입력 버튼의 value 속성 내용을 반환하고 수정할 수 있습니다.

실전 예제

다음 예제는 버튼을 클릭하면 동일한 버튼이 새로 복제되어 화면에 추가되는 코드입니다.

<!DOCTYPE html>
<html>
<head>
<title>HTML DOM Input Button Object</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:60%;
        font-weight:bold;
    }
    .show-msg{
        font-weight:bold;
        font-size:1.4rem;
        color:#ffc107;
    }
</style>
</head>
<body>
<h1>Input Button Object Example</h1>
<input type="button" onclick="createReplica()" class="btn" value="Click to replicate me">
<div class="show-msg"></div>
<script>
    function createReplica() {
        var newButton = document.createElement("INPUT");
        newButton.setAttribute("type","button");
        newButton.setAttribute("class","btn");
        newButton.setAttribute("value","Click to replicate me");
        newButton.setAttribute("onclick","createReplica()");
        document.body.appendChild(newButton);
    }
</script>
</body>
</html>

실행 결과

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

HTML DOM 입력 버튼(Input Button) 객체 완벽 정리

"Click to replicate me" 버튼을 클릭할 때마다 document.createElement()를 통해 동일한 디자인과 기능을 가진 새로운 버튼이 페이지 하단에 계속 추가됩니다.

HTML DOM 입력 버튼(Input Button) 객체 완벽 정리

이처럼 DOM Input Button 객체를 사용하면 사용자의 상호작용에 반응하여 버튼을 동적으로 생성·제어하는 것이 매우 간단해집니다.