티스토리 뷰


 
오늘은 요소의 속성 값을 가져오는 방법인 getAttribute()에 이어 요소의 속성을 설정하는 방법인 setAttribute()에 대해 다룰 것이다.
 

1. setAttribute() 문법


element.setAttribute(<attributeName>, <attributeValue>);

이 메소드는 두 개의 필수 매개변수가 있다. 하나씩 살펴보자.

 

setAttribute() 매개변수

  • attributeName:  “href”, “type”, “style” 와 같이 속성명을 지정하면 된다.
  • attributeValue: 지정한 속성명에 대한 속성값을 지정하면 된다. 만약 attributeName이 “href” 이면 값은 “https://shinyks.com”, 속성이 “type” 이면 값으로 “text” 등을 넣으면 된다.

 

 

2. 예제


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>setAttribute Example</title>
</head>
<body>

<div id="example">Example Div</div>

<button onclick="addAttribute()">Add Attribute</button>

<script>
    function addAttribute() {
        // 요소를 가져온다.
        let element = document.getElementById('example');

        // setAttribute()를 사용하여 'data-title' 속성을 추가한다.
        element.setAttribute('data-title', 'Example Title');

        // 요소에 새로 추가된 속성 값을 콘솔에 출력한다.
        console.log("data-title 속성의 값:", element.getAttribute('data-title'));
    }
</script>

</body>
</html>

 

개발자 도구(f12)를 확인해보면 "Example Title"이 출력된 것을 확인할 수 있다.

 

+) getAttribute()는 요소의 속성 값을 가져오는 메소드이다. 아래의 글에서 관련 내용을 확인 할 수 있다.

https://codingtoddlerr.tistory.com/194

 

 

 

3. 정리


setAttribute() 메소드는 HTML 요소에 속성을 할당할 때 사용한다. 또한 이 메소드는 리턴값이 없다.