정의 및 사용 방법
setAttribute() 함수는
DOM 요소에 속성 값을 설정하는 함수입니다.
특징
구문
element.setAttribute(attributeName, value)
매개변수
반환 값
없습니다. 즉, undefined를 반환합니다.
DOM 요소에서 속성 값을 가져오려면 getAttribute() 함수를 사용하세요.
DOM 요소에서 특정 속성을 제거하려면 removeAttribute() 함수를 사용하세요.
예제
상황별 예제로 살펴보겠습니다.
지정된 속성이 이미 존재하는 경우
요소에서 지정된 속성이 이미 존재하는 경우 값이 업데이트됩니다.
<input type="password" value="test">
<button type="button">비밀번호 보기</button>
const elem = document.querySelector("input");
const button = document.querySelector("button");
button.addEventListener("click", () => { // 버튼 클릭 이벤트
/* 버튼을 클릭하면,
input 요소의 type 속성 값이 password에서 text로 변경됩니다. */
elem.setAttribute("type", "text");
});
코드 부연설명
querySelector() 함수는 지정한 CSS 선택자와 일치하는 첫 번째 요소 객체를 반환합니다.
"비밀번호 보기" 버튼을 클릭해 보세요!
지정된 속성이 없는 경우
요소에서 지정된 속성이 없는 경우에는 지정된 이름과 값으로 새 속성이 추가됩니다.
<input type="text">
<button type="button">test 입력하기</button>
const elem = document.querySelector("input");
const button = document.querySelector("button");
button.addEventListener("click", () => { // 버튼 클릭 이벤트
/* 버튼을 클릭하면,
input 요소의 value 속성이 없지만,
value 속성이 추가되고 값이 test로 변경됩니다. */
elem.setAttribute("value", "test");
});
"test 입력하기" 버튼을 클릭해 보세요!
여러 속성을 설정하기
각 속성은 setAttribute() 함수를 각각 호출하여 설정합니다.
const element = document.getElementById("example-id");
// 첫 번째 속성 설정
element.setAttribute("alt", "Set your alt");
// 두 번째 속성 설정
element.setAttribute("title", "Set your title");
// 세 번째 속성 설정
element.setAttribute("src", "/images/image.jpg");
값을 필요로 하지 않는 부울 속성(Boolean attribute)일 경우
<input type="text">
<button type="button">input box 숨기기</button>
const elem = document.querySelector("input");
const button = document.querySelector("button");
button.addEventListener("click", () => { // 버튼 클릭 이벤트
/* 버튼을 클릭하면,
input 요소에 hidden 속성을 추가하기
값은 빈 문자열("")로 설정합니다. */
elem.setAttribute("hidden", "");
});
"input box 숨기기" 버튼을 클릭해 보세요!
주의할 점
element.setAttribute("style", "background-color:blue;");
대신 자바스크립트의 style 속성을 사용하세요.
element.style.backgroundColor = "blue";
브라우저 호환성
| 메서드 |
데스크탑 Chrome
|
데스크탑 Edge
|
데스크탑 Firefox
|
Safari
|
|---|---|---|---|---|
setAttribute()
|
1 | 12 | 1 | 1 |
명세서
| 명세서 사양 | |
|---|---|
setAttribute()
|
DOM Standard #ref-for-dom-element-setattribute① |