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

HTML DOM removeAttributeNode() 메서드 – 문법, 예제, 실행 결과까지 한눈에

HTML DOM의 removeAttributeNode() 메서드는 HTML 문서에서 지정된 요소로부터 매개변수에 명시한 속성 노드를 제거하고, 제거된 속성을 Attr 노드 객체 형태로 반환합니다.

문법

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

node.removeAttributeNode(attributeNode);

매개변수 설명

  • attributeNode: 제거하려는 속성 노드입니다. 보통 getAttributeNode() 메서드로 먼저 가져온 Attr 객체를 인자로 전달합니다.

예제

다음 예제를 통해 removeAttributeNode() 메서드가 실제로 어떻게 동작하는지 살펴보겠습니다.

<!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 removeAttributeNode() 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() {
        var p=document.querySelector("p");
        var pAtt=p.getAttributeNode("style");
        p.removeAttributeNode(pAtt);
    }
</script>
</body>
</html>

실행 결과

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

HTML DOM removeAttributeNode() 메서드 – 문법, 예제, 실행 결과까지 한눈에

"Remove Attribute" 버튼을 클릭하면 <p> 요소에서 style 속성이 제거됩니다. 그 결과 빨간색 텍스트 스타일이 사라지고 해당 단락은 브라우저 기본 스타일로 되돌아갑니다.

HTML DOM removeAttributeNode() 메서드 – 문법, 예제, 실행 결과까지 한눈에

핵심 포인트 정리

  • removeAttributeNode()는 속성 이름 문자열이 아닌 Attr 노드 객체를 인자로 받습니다.
  • 제거 대상 속성은 getAttributeNode() 메서드를 사용해 미리 가져와야 합니다.
  • 메서드 호출 후에는 제거된 속성이 Attr 객체로 반환되므로, 필요하다면 이후 다른 용도로 활용할 수 있습니다.