JavaScript/DOM

[JavaScript]HTML 애트리뷰트(Attribute) 제거하는 방법

DevStory 2022. 12. 7.

HTML 애트리뷰트(Attribute) 제거하는 방법

이번 포스팅은 JavaScript에서 HTML 애트리뷰트(Attribute)를 제거하는 몇 가지 방법을 소개합니다.


removeAttribute() - 애트리뷰트 이름을 전달

가장 일반적인 방법으로 선택한 요소에서 removeAttribute() 메서드를 호출하여 특정 애트리뷰트를 제거할 수 있습니다.

selectedNode.removeAttribute(name);

매개변수

name: 애트리뷰트의 이름입니다.

 

반환 결과

삭제 여부와 관계없이 undefined를 반환합니다.

 

아래는 id가 "input-text"인 HTML 요소의 name 애트리뷰트를 removeAttribute() 메서드로 제거하는 예제입니다.

<input id="input-text" name="input-name" custom="custom-attr" />
const inputNode = document.getElementById("input-text");

// name 애트리뷰트 제거하기 전
console.log(inputNode.hasAttribute('name')); // true

console.log(inputNode.removeAttribute("name")); // undefined

// name 애트리뷰트 제거 후
console.log(inputNode.hasAttribute('name')); // false

removeAttribute() 메서드는 애트리뷰트가 존재하지 않더라도 undefined를 반환합니다. 따라서, 애트리뷰트가 정상적으로 제거되었는지 확인하려면 hasAttribute() 메서드를 사용합니다.

 

그리고 기본 애트리뷰트인 disabled와 readonly는 모든 값을 true로 간주합니다. diabled와 readonly 애트리뷰트의 값을 false로 변경하고 싶다면 setAttribute() 메서드가 아닌 removeAttribute() 메서드를 호출하여 애트리뷰트를 완전히 제거합니다.


모든 애트리뷰트 제거

removeAttribute() 메서드는 하나의 애트리뷰트만 제거할 수 있습니다. 선택한 요소의 모든 애트리뷰트를 제거하고 싶다면 반복문에서 removeAttribute() 메서드를 호출합니다.

 

방법 1. forEach() 메서드 사용

const inputNode = document.getElementById("input-text");

[...inputNode.attributes].forEach((attr) =>
  inputNode.removeAttribute(attr.name)
);

 

방법 2. while문 사용

const inputNode = document.getElementById("input-text");

while (inputNode.attributes.length > 0) {
  inputNode.removeAttribute(inputNode.attributes[0].name);
}

removeAttributeNode() - Attr 객체를 전달

두 번째 방법으로 선택한 요소에서 removeAttributeNode() 메서드 호출 후 Attr 객체를 전달하여 특정 애트리뷰트를 제거할 수 있습니다.

const removeAttr = selectedNode.removeAttributeNode(attribute);

매개변수

attribute: Attr 객체입니다.

 

반환 결과

제거된 애트리뷰트를 Attr 객체로 반환합니다.

 

예외 및 에러

Attr 객체가 아닌 타입을 전달하거나 노드에 존재하지 않은 애트리뷰트를 전달하면 TypeError가 발생합니다.

 

아래는 id가 "input-text"인 HTML 요소의 name 애트리뷰트를 removeAttributeNode() 메서드로 제거하는 예제입니다.

<input id="input-text" name="input-name" custom="custom-attr" />
const inputNode = document.getElementById("input-text");

// name 애트리뷰트 제거하기 전
console.log(inputNode.getAttributeNames());
// ["id", "name", "custom"]

const nameAttr = inputNode.getAttributeNode("name");
console.log(inputNode.removeAttributeNode(nameAttr));
// Attr {namespaceURI: null, prefix: null, localName: "name", name: "name", value: "input-name"…}

// name 애트리뷰트 제거 후
console.log(inputNode.getAttributeNames());
// ["id", "custom"]

정리

  • removeAttribute() 메서드에 애트리뷰트 이름을 전달하여 애트리뷰트를 제거할 수 있습니다.
  • removeAttributeNode() 메서드에 Attr 객체를 전달하여 애트리뷰트를 제거할 수 있습니다.
반응형

댓글