티스토리 뷰

 

 

 


목차

 

1. getAttribute() 문법

2. 예제

3. 정리


 

 

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

1. getAttribute() 문법


element.getAttribute(attributename);

 

여기서 attributename은 얻고자 하는 속성 값에 해당하는 속성 이름이다.

 

 

 

2. 예제


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

<div id="example" data-title="Example Title">Example Div</div>

<script>
    // 요소를 선택하기
    let element = document.getElementById('example');

    // 'data-title' 속성의 값을 가져오기
    let titleValue = element.getAttribute('data-title');

    // 가져온 속성 값을 출력하기
    console.log("data-title 속성의 값:", titleValue);
</script>

</body>
</html>

 

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

 

getAttribute() 메소드를 사용하면 버튼 요소의 onclick같은 속성 값도 가져올 수 있다. 다음의 예제는 <button> 요소의 onclick 속성 값을 가져와 콘솔창에 출력하는 코드이다.

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

<button id="myButton" onclick="showAttribute()">Click Me</button>

<script>
    function showAttribute() {
        // 클릭된 버튼 요소를 가져온다.
        let button = document.getElementById('myButton');

        // 버튼의 onclick 속성 값을 가져온다.
        let onclickValue = button.getAttribute('onclick');

        // 가져온 속성 값을 콘솔에 출력한다.
        console.log("onclick 속성의 값:", onclickValue);
    }
</script>

</body>
</html>

 

 

3. 정리


getAttribute() 메소드는 지정된 HTML 요소의 속성 "값"을 가져올 수 있다. 

만약 요소에 매개변수로 주어진 속성이 없다면 null을 리턴한다.