JavaScript/DOM

[JavaScript]HTML 애트리뷰트(Attribute) 가져오는 방법

DevStory 2022. 12. 7.

HTML 애트리뷰트(Attribute) 가져오는 방법

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


getAttribute() - 애트리뷰트 이름으로 값 가져오기

특정 HTML 요소를 선택한 다음 getAttribute() 메서드를 호출하여 HTML 애트리뷰트의 값을 가져올 수 있습니다.

 

아래는 세 개의 애트리뷰트를 가지는 <input> 태그입니다.

<input id="input-text" name="content" data-value="hello" />
const inputNode = document.getElementById("input-text");

console.log(inputNode.getAttribute("id"));         // input-text 
console.log(inputNode.getAttribute("name"));       // content
console.log(inputNode.getAttribute("data-value")); // hello
console.log(inputNode.getAttribute("custom"));     // null

getAttribute() 메서드에 애트리뷰트의 이름을 전달하면 매핑되는 값을 반환합니다. 애트리뷰트가 존재하지 않으면 null을 반환합니다.


getAttributeNames() - 애트리뷰트 이름 가져오기

특정 HTML 요소에 설정된 모든 애트리뷰트 이름을 가져오려면 getAttributeNames() 메서드를 호출합니다.

 

아래는 세 개의 애트리뷰트를 가지는 <input> 태그입니다.

<input id="input-text" name="content" data-value="hello" />
const inputNode = document.getElementById("input-text");

console.log(inputNode.getAttributeNames());
// ["id", "name", "data-value"]

getAttributeNames() 메서드는 매개변수가 존재하지 않으며, 애트리뷰트 이름을 배열로 반환합니다.

 

만약 아래 예제처럼 HTML 애트리뷰트가 존재하지 않으면, 빈 배열을 반환합니다.

<body>
  <input />
  <script src="src/index.js"></script>
</body>
// <body> 태그의 첫 번째 자식 노드 가져오기
const inputNode = document.body.firstElementChild;

console.log(inputNode.getAttributeNames()); // []

 

아래 예제는 getAttributeNames() 메서드로 애트리뷰트 이름을 가져온 다음 반복문을 사용하여 애트리뷰트 이름과 매핑되는 값을 출력합니다.

<input id="input-text" name="content" data-value="hello" />
const inputNode = document.getElementById("input-text");

for(const name of inputNode.getAttributeNames()) {
  const value = inputNode.getAttribute(name);
  console.log(name + ": " + value);
}

[실행 결과]


getAttributeNode() - Attr 객체 가져오기

마지막 방법으로 getAttributeNde() 메서드를 사용하여 Attr 타입의 객체를 가져올 수 있습니다.

<input id="input-text" name="content" data-value="hello" />
const inputNode = document.getElementById("input-text");

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

console.log(inputNode.getAttributeNode("id").value);
// input-text

console.log(inputNode.getAttributeNode("custom")); 
// null

getAttribute() 메서드와 마찬가지로 애트리뷰트가 존재하지 않으면 null을 반환합니다. Attr 객체가 아닌 애트리뷰트의 값을 가져와야 하는 경우 getAttributeNode() 메서드보다 getAttribute() 메서드를 사용하는 것이 좋습니다.


정리

  • getAttribute() 메서드는 애트리뷰트 이름과 매핑되는 값을 반환합니다.
  • getAttributeName() 메서드는 애트리뷰트의 이름을 배열로 반환합니다.
  • getAttributeNode() 메서드는 애트리뷰트 이름과 매핑되는 Attr 객체를 반환합니다.
반응형

댓글