WebDevelop/jQuery

jQuery .attr() vs .prop()

쥬리엘 2015. 4. 27. 13:30

jQuery에서 .attr()과 .prop()은 사용시 몇가지 차이점이 있다.


.attr()의 경우 이름 그대로 attribute를 컨트롤 하기위함이고, .prop()의 경우 property를 컨트롤할때 사용한다.


간단한 예를 들어서..


<input type="checkbox" id="check" checked="checked" />
<label for="check">Check Me...</label>
$('#check').change(function() {
    var $input = $(this);
    console.log(".attr('checked'): " + $input.attr('checked'));
    console.log(".prop('checked'): " + $input.prop('checked'));
    console.log(".is('checked'): " + $input.is('checked'));
}).change();


위 체크박스를 클릭시..


.attr()의 경우 체크여부와 상관없이 항상 'checked'만을 리턴하고..

.prop()의 경우 체크여부에 따라 true, false를 리턴한다.


단, jquery 1.6 이전 버전엔 .prop()이 없으니 버전을 확인하고 사용해야한다.