[JS] 13. getAttribute와 setAttribute _ 속성 컨트롤 메서드

Kang So Hyun·2023년 4월 23일
0

📌 getAttribute('속성명')

  • 문서객체의 태그 속성값을 얻어오는 메서드 / 게터

✏️ 예시

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>getAttribute</title>
    </head>
    <style>
        .get { color: #ff0000; }
    </style>
    <body>
        <h1 class="get">getAttribute</h1>
        <p id="demo"></p>
        
        <script>
                var x = document.getElementsByTagName("h1")[0].getAttribute("class"); //값이 h1인 요소의 class 속성 값을 변수 x에 저장
                document.getElementById("demo").innerHTML = x; //id의 값이 demo인 요소에  값을 가져와서 출력
        </script>
    </body>
</html>

🖥️ 결과

📌 setAttribute('속성명',값)

  • 문서객체의 태그 속성값을 변경시키는 메서드 / 세터

✏️ 예시

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>setAttribute</title>
    </head>
    <body>
        <input type="checkbox">
        <span>기본 체크 박스</span>
        <input type="checkbox" id="check-test">
        <span class="check-text">체크된 박스</span>
        <script>
            let checkTest = document.querySelector('#check-test');
            checkTest.setAttribute('checked',true);
        </script>
    </body>
</html>

🖥️ 결과

profile
중국어랑 코딩하기 (❛ ֊ ❛„)

0개의 댓글