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

HTML DOM removeAttribute() 메서드 – 요소의 속성을 제거하는 방법

HTML DOM의 removeAttribute() 메서드는 HTML 문서 내 지정한 요소에서, 매개변수로 전달된 이름과 일치하는 속성(attribute)을 제거합니다. 예를 들어 인라인 스타일이나 클래스, ID 같은 속성을 자바스크립트만으로 동적으로 삭제할 수 있어, UI 상태를 변경할 때 유용하게 활용됩니다.

구문(Syntax)

removeAttribute() 메서드의 기본 구문은 다음과 같습니다.

node.removeAttribute(attributeName);

매개변수: attributeName에는 제거하고자 하는 속성의 이름을 문자열로 전달합니다. 해당 속성이 요소에 존재하지 않더라도 이 메서드는 오류를 발생시키지 않고 조용히 종료되므로, 별도의 존재 여부 확인 없이 안전하게 호출할 수 있습니다.

예제(Example)

아래 예제는 removeAttribute() 메서드를 사용하여 <p> 요소의 style 속성을 제거하는 과정을 보여줍니다.

<!DOCTYPE html>
<html>
<head>
<style>
    html{
        height:100%;
    }
    body{
        text-align:center;
        color:#fff;
        background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) center/cover no-repeat;
        height:100%;
    }
    .btn{
        background:#0197F6;
        border:none;
        height:2rem;
        border-radius:2px;
        width:35%;
        margin:2rem auto;
        display:block;
        color:#fff;
        outline:none;
        cursor:pointer;
    }
</style>
</head>
<body>
<h1>DOM removeAttribute() method Demo</h1>
<p style="color:#db133a;font-size:1.2rem;">Hi! I'm a para element in HTML with some random text</p>
<button onclick="remove()" class="btn">Remove Attribute</button>
<script>
    function remove() {
        document.querySelector("p").removeAttribute("style");
    }
</script>
</body>
</html>

출력 결과(Output)

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

HTML DOM removeAttribute() 메서드 – 요소의 속성을 제거하는 방법

초기 상태에서는 <p> 요소에 style 속성이 적용되어 빨간색 텍스트가 표시됩니다. 여기서 “Remove Attribute” 버튼을 클릭하면 다음과 같이 <p> 요소에서 style 속성이 제거됩니다.

HTML DOM removeAttribute() 메서드 – 요소의 속성을 제거하는 방법

버튼을 클릭한 후 문단의 글자 색상과 크기가 기본값으로 되돌아간 것을 확인할 수 있습니다. 이는 document.querySelector("p")로 선택한 요소에서 removeAttribute("style")가 호출되어 인라인 스타일이 완전히 삭제되었기 때문입니다.

정리

removeAttribute() 메서드는 setAttribute(), getAttribute(), hasAttribute()와 함께 DOM 속성을 다룰 때 자주 사용되는 핵심 API입니다. 불필요해진 속성을 깔끔하게 정리하거나, 조건에 따라 요소의 스타일·동작을 토글하는 기능을 구현할 때 활용해 보세요.