STUDY

JavaScript | prop(), attr()

devvnn 2022. 4. 26. 14:11
.prop()

- 속성값을 추가하거나 가져오는 메서드

 

 

예제1

// HTML
<p><a href="#none" class="link">버튼</a></p>

 

// JS
var $goLink = $('.link'); console.log($goLink.attr('href'));
// #none 출력 

console.log($goLink.prop('href')); 
// http://localhost:63342/Project/srcFactory/study/test.html#none 출력

 

 

예제2

// HTML
<input type="checkbox" name="" id="chk" checked="checked">

 

// JS
var $checkbox = $('#chk'); 

console.log($checkbox.attr('checked')); // checked 
console.log($checkbox.prop('checked')); // true

 

 

 

attr()

// HTML
<input type="checkbox" id="example" checked="checked">

 

// JS
// attr()
var text = $("input[type=text]");
console.log(chk.attr("id"));		// example
console.log(chk.attr("type"));		// text
console.log(chk.attr("checked"));	// checked

// prop()
var text = $("input[type=text]");
console.log(chk.prop("id"));		// example
console.log(chk.prop("type"));		// text
console.log(chk.prop("checked"));	// true

 

 

 

prop() vs attr()

- attr() :  HTML 속성 (Attribute) 취급 / HTML attribute 값이 모두 String으로 넘어옴

 

- prop() : javascript 프로퍼티 (Property) 취급 / 프로퍼티를 사용할 때(활성화, 체크 여부 등을 제어하는 업무에 사용), js 프로퍼티 값이 넘어오기 때문에 date, function, boolean 형식으로 가져올 수 있음

 

  attr() prop()
사용목적 일반적인 태그 속성의 값을 변경할 때 사용 태그속성에 따라서 기능이 제어되는 속성 변경 시 사용
특징 HTML의 속성을 취급(HTML Element에 있는 정보) JavaScript의 프로퍼티를 취급
리턴타입 HTML attribute 값이 모두 String으로 넘어옴 boolean, date, function 등의 데이터 타입이 그대로 넘어옴
실행속도 attr()에 비해 prop()이 2.5배 빠름
사용예시 1. class 변경
    $(":checkbox").attr("class","large_checkbox");
 1. checkbox 상태 변경 

    $(":checkbox").prop("checked",true); 


 2. combobox disabled 속성의 true, false 상태 변경 

    $('#combobox').prop('disabled', true);
결론 attr()은 요소의 현재 html의 원래 값을 제공하므로
 javascript, jquery를 통해 수정된 요소의 값을 가져와야 할 때는 prop()을 사용하는 게 좋다.

 

정리하자면, HTML 관련된 것은 attr() / JavaScript 관련된 것은 prop()

 

 

Reference

https://funfunit.tistory.com/72

https://yeonzzy.tistory.com/21