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

HTML DOM input 버튼 type 속성 – 버튼 유형 확인하는 방법

HTML DOM에서 input 버튼의 type 속성은 해당 입력 요소가 어떤 유형(type)인지 문자열로 반환합니다. 반환될 수 있는 값은 총 세 가지로, "button"(일반 버튼), "submit"(폼 제출 버튼), "reset"(폼 초기화 버튼)입니다.

이 속성은 읽기 전용이며, 자바스크립트를 통해 동적으로 생성된 버튼이나 사용자가 클릭한 버튼의 실제 유형을 확인해야 할 때 특히 유용합니다.

문법(Syntax)

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

object.type

예제(Example)

아래 예제는 input 버튼의 type 속성을 활용하여 버튼의 유형을 화면에 출력하는 방법을 보여줍니다.

<!DOCTYPE html>
<html>
<head>
<title>HTML DOM type 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:40%;
    }
    .show-type{
        font-weight:bold;
        font-size:1.4rem;
        color:#ffc107;
    }
</style>
</head>
<body>
<h1>type Property Example</h1>
<input type = "submit" onclick = "getType()" class = "btn" value = "Click me to know about my type">
<div class="show-type"></div>
<script>
    function getType() {
        var btnType = document.querySelector(".btn").type;
        document.querySelector(".show-type").innerHTML = btnType;
    }
</script>
</body>
</html>

코드 설명

위 예제의 핵심 로직은 getType() 함수에 있습니다. document.querySelector(".btn")으로 버튼 요소를 선택한 뒤, .type 속성 값을 읽어와서 .show-type 클래스를 가진 div 영역에 표시합니다. 이 버튼은 HTML에서 type="submit"으로 정의되었으므로, 클릭 시 화면에 submit이라는 값이 출력됩니다.

실행 결과(Output)

위 코드를 실행하면 다음과 같은 화면이 나타납니다.

HTML DOM input 버튼 type 속성 – 버튼 유형 확인하는 방법

여기서 "Click me to know about my type"(내 유형을 알려줘) 버튼을 클릭하면, 해당 input 버튼의 유형이 아래 영역에 표시됩니다.

HTML DOM input 버튼 type 속성 – 버튼 유형 확인하는 방법

정리

HTML DOM의 input 버튼 type 속성은 별도의 매개변수 없이 간단히 호출할 수 있으며, 모든 주요 브라우저(Chrome, Firefox, Safari, Edge, Opera)에서 지원됩니다. 폼 유효성 검사나 동적 UI 처리 시 버튼의 역할을 구분해야 하는 상황에서 활용하면 좋습니다.