울음참고 개발공부
article thumbnail
Published 2024. 3. 18. 15:44
attr() 과 prop() 의 차이 jQuery && JS
728x90

 

 

Attribute (attr) 

  • HTML 태그에서 속성(attribute)은 요소의 초기 상태를 정의
  • HTML 마크업 안에 작성된 상태 그대로를 의미

 

<input type="checkbox" checked>  // attribute: checked 된 상태자체

 

 

Property (prop) 

  • JavaScript 에서 속성(property)은 요소의 현재 상태를 나타냄
  • DOM 요소의 속성(property)은 JavaScript 에서 제어할 수 있는 동적인 값

 

<input type="checkbox" checked>  // property : 사용자가 변경할수있는 상태 

 

 

 

 

 

예시  )

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <input type="checkbox" id="myCheckbox" checked>
    <button id="checkButton">Check Status</button>
    <button id="toggleButton">Toggle Check</button>
    <p id="status"></p>

    <script>
        $(document).ready(function() {
            $('#checkButton').on('click', function() {
                // DOM 을 로드한 후 초기 상태
                var attrChecked = $('#myCheckbox').attr('checked');
                // 현재 상태 
                var propChecked = $('#myCheckbox').prop('checked');

                $('#status').text('Attribute: ' + attrChecked + ', Property: ' + propChecked);
            });

            $('#toggleButton').on('click', function() {
                // check box 상태 변경
                var isChecked = $('#myCheckbox').prop('checked');
                $('#myCheckbox').prop('checked', !isChecked);
            });
        });
    </script>
</body>
</html>

 

 

 

'<input type="checkbox" checked>' 로 준 상태 

 

 

Attribute 는 HTML 에 작성된 상태 그대로를 의미하기 때문에, 

<input type="checkbox"> 상태에서 값을 가져오려 한다면 'undefind' 가 뜰 것임 

 

 

 

 

checked=false 가 되었을 때, property는 현재 상태값을 가져온다

 

 

 

 

 

728x90
profile

울음참고 개발공부

@메각이

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!