DOM의 setAttributeNode() 메서드는 HTML 문서에서 특정 요소에 매개변수로 전달된 속성(Attribute) 노드를 설정하고, 그 결과를 Attr 노드 객체 형태로 반환합니다. 일반적인 setAttribute() 메서드와 달리, 이 메서드는 createAttribute()로 미리 생성한 속성 노드를 그대로 요소에 부착할 때 유용하게 사용됩니다.
문법(Syntax)
setAttributeNode() 메서드의 기본 문법은 다음과 같습니다.
node.setAttributeNode(attributeNode);
- attributeNode: createAttribute() 메서드로 생성한 Attr 노드를 의미합니다.
예제(Example)
아래 예제는 버튼을 클릭하면 <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 setAttributeNode() method Demo</h1>
<p>Hi! I'm a para element in HTML with some random text</p>
<button onclick="set()" class="btn">Set Attribute</button>
<script>
function set() {
var p=document.querySelector("p");
var attr=document.createAttribute("style");
attr.value="color:#db133a;font-size:1.2rem;";
p.setAttributeNode(attr);
}
</script>
</body>
</html>코드 설명
- document.querySelector("p") – 문서에서 첫 번째 <p> 요소를 선택합니다.
- document.createAttribute("style") – 'style'이라는 이름의 새로운 속성 노드를 생성합니다.
- attr.value – 생성된 속성 노드에 글자 색상(#db133a)과 폰트 크기(1.2rem) 값을 지정합니다.
- p.setAttributeNode(attr) – 해당 <p> 요소에 style 속성 노드를 설정합니다.
실행 결과(Output)
위 코드를 실행하면 다음과 같은 초기 화면이 출력됩니다.

여기서 "Set Attribute" 버튼을 클릭하면 <p> 요소에 style 속성이 적용되어 글자 색상과 크기가 즉시 변경됩니다.

정리
setAttributeNode() 메서드는 기존에 존재하는 같은 이름의 속성이 있다면 이를 대체하고, 없다면 새로 추가합니다. 속성을 문자열이 아닌 Attr 노드 단위로 다뤄야 하는 경우나, 속성 노드를 재사용해야 하는 상황에서 setAttribute()보다 더 세밀한 제어가 가능하다는 장점이 있습니다.