Programing/Front(HTML, CSS, JS)

[jQuery] .attr()과 .prop()의 차이

hye3193 2023. 12. 19. 18:19

.attr(): HTML의 속성을 다룬다

.prop(): JavaScript의 프로퍼티(속성)를 다룬다

* 자바스크립트에서 프로퍼티란 {키: 값} 을 의미

<checkbox id="agree" type="checkbox" checked />
var $checkbox = $('#agree');
alert($checkbox.attr('checked'));
alert($checkbvox.prop('checked'));

출력 결과

attr(): "checked"

→ HTML에서의 checked의 속성을 표시(checked)

prop(): true

→ JavaScript에서의 checked의 프로퍼티를 표시(checked: true)

 

 

<a id="get_comment" href="#comments">코멘트</a>
var $comment = $('#get_comments');
alert($comment.attr('href'));
alert($comment.prop('href'));

출력 결과

attr(): "#comments"

prop(): "http://test.com/path/page#comments"

 

HTML 상에서의 속성 값은 #comments와 같은 형태로(HTML에 작성된 대로) 출력되었지만

JavaScript 상에서의 속성 값은 전체 주소값이 출력되었다

 

 

attr()는 string 형태로 값을 가져오지만

prop은 다양한 데이터 형태(bool, int 등등)를 가질 수 있다

 

따라서 HTML에서의 속성명을 가져오고 싶으면 attr(),

JavaScript에서의 속성값을 가져오고 싶으면 prop을 사용하면 된다

 

추가로 검색해보니 attr보다 prop 함수의 처리 속도가 더 빠르다고 한다

 

 

 

참고: https://electronic-moongchi.tistory.com/41