HTML DOM setAttribute() 메서드
❮ 요소 개체예시
값이 "democlass"인 class 속성을 <h1> 요소에 추가합니다.
document.getElementsByTagName("H1")[0].setAttribute("class", "democlass");
속성을 설정하기 전에:
Hello World
속성을 설정한 후:
Hello World
아래에서 더 많은 "직접 사용해 보기" 예를 살펴보세요.
정의 및 사용
setAttribute() 메서드는 지정된 속성을 요소에 추가하고 지정된 값을 제공합니다.
지정된 속성이 이미 존재하는 경우 값만 설정/변경됩니다.
참고: 이 방법을 사용하여 값이 있는 스타일 속성을 요소에 추가할 수 있지만 인라인 스타일 대신 Style 개체의 속성을 사용하는 것이 좋습니다 . 스타일 속성:
나쁜:
element.setAttribute("style", "background-color: red;");
좋은:
element.style.backgroundColor = "red";
팁: removeAttribute() 메소드를 사용 하여 요소에서 속성을 제거하십시오.
팁: setAttributeNode() 메서드 도 참조하세요 .
브라우저 지원
표의 숫자는 이 방법을 완전히 지원하는 첫 번째 브라우저 버전을 지정합니다.
Method | |||||
---|---|---|---|---|---|
setAttribute() | Yes | 8.0 | Yes | Yes | Yes |
통사론
element.setAttribute(attributename, attributevalue)
매개변수 값
Parameter | Type | Description |
---|---|---|
attributename | String | Required. The name of the attribute you want to add |
attributevalue | String | Required. The value of the attribute you want to add |
기술적 세부 사항
반환 값: | 반환 값 없음 |
---|---|
DOM 버전 | 핵심 레벨 1 요소 개체 |
더 많은 예
예시
입력 필드를 입력 버튼으로 변경:
document.getElementsByTagName("INPUT")[0].setAttribute("type", "button");
속성을 설정하기 전에:
속성을 설정한 후:
예시
값이 "www.w3schools.com"인 href 속성을 <a> 요소에 추가합니다.
document.getElementById("myAnchor").setAttribute("href", "https://www.w3schools.com");
속성을 설정하기 전에:
Go to w3schools.com
속성을 설정한 후:
예시
<a> 요소에 target 속성이 있는지 알아보세요. 그렇다면 대상 속성의 값을 "_self"로 변경하십시오.
// Get the <a> element with id="myAnchor"
var x = document.getElementById("myAnchor");
// If the <a> element has a target attribute, set the value to "_self"
if (x.hasAttribute("target")) {
x.setAttribute("target", "_self");
}
관련 페이지
HTML 튜토리얼: HTML 속성
HTML DOM 참조: getAttribute() 메서드
HTML DOM 참조: hasAttribute() 메서드
HTML DOM 참조: removeAttribute() 메서드
❮ 요소 개체