jQuery

JQuery .attr() .prop()의 차이

xxoyeong 2020. 8. 31. 21:43

.attr()는 HTML의 속성을 취급   속성은 HTML 요소에 대한 추가 정보를 전달

<input id="so" type="text" value="javascript"/>

여기서 id, type, value는 속성

attr은 setAttribute, getAttribute에 대응되는 메소드

 

ex)

<a id="target" href="http://www.naver.com">opentutorials</a>

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

<script>

var t = $('#target');

console.log(t.attr('href')); // href="http://www.naver.com

t.attr('title', 'opentutorials.org'); // title 속성의 값을 설정한다.

t.removeAttr('title'); // title 속성을 제거한다.

</script>

 

 

.prop()는 JavaScript 프로퍼티를 취급 

 

ex) 

 

<a id="t1" href="./demo.html">opentutorials</a>

<input id="t2" type="checkbox" checked="checked" />

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

<script>

// 현재 문서의 URL이 아래와 같다고 했을 때

// http://localhost/jQuery_attribute_api/demo2.html

 

var t1 = $('#t1');

console.log(t1.attr('href')); // ./demo.html

console.log(t1.prop('href')); // http://localhost/jQuery_attribute_api/demo.html

 

var t2 = $('#t2');

console.log(t2.attr('checked')); // checked

console.log(t2.prop('checked')); // true

</script>

 

제이쿼리로 엘리먼트 제어했을때 좋은점

-코드간결

-프로퍼티의 이름으로 어떤 것을 사용하건 올바른 것으로 교정해준다