Javascript

[$,JQuery] .attr()과 .prop()의 차이점

ChrisJang 2021. 2. 1. 16:38
반응형

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

 

jQuery 를 사용하다 보면 태그들의 속성값을 정의하거나 가져오기 위해 .attr() 함수를 사용하는 경우가 많을 것이다.

그런데 jQuery 1.6 이후 부터 .attr() 함수가 용도에 따라 .attr()  .prop() 으로 분리 되었다.

 

그렇다면 .attr() 과 .prop() 의 차이는 무엇일까?

.attr() : html 의 속성(attribute)을 다룬다.

.prop() : javascript 프로퍼티(property)를 다룬다.

 


[예 1]
1. 
<a id="get_comment" href="#comments">코멘트</a>

2. var $comment = $('#get_comments');

3. alert($comment.attr('href')); // href 속성 값을 표시

4. alert($comment.prop('href')); // href 프로퍼티 값을 표시


 

위 예제1 에서 3, 4번의 alert 결과는 어떻게 될까?

3번 alert 의 .attr() 값은 "#comments"

4번 alert 의 .prop() 값은 "http://test.com/path/page#comments" 가 된다.

 



[예 2]

1. <checkbox id="agree" type="checkbox" checked />

2. var $checkbox = $('#agree');

3. alert($checkbox.attr('checked')); // checked 속성 값을 표시

4. alert($checkbvox.prop('checked')); // checked 프로퍼티 값을 표시


위 예제 2 에서

3번 alert 의 .attr() 값은 "checked"

4번 alert 의 .prop() 값은 "true" 가 된다.

 

 

결론적으로 html 에 쓴 속성 값을 다루고 싶을때는 .attr() 함수를 사용하고, 그 외에 javascript 의 프로퍼티 값을 사용할 경우는 .prop() 함수를 사용하면 된다.

 

 

 

 

 

 

 


출처:

electronic-moongchi.tistory.com/41

반응형