본문 바로가기

javascript/jQuery

[jQuery] attribute vs property 그리고 .attr() 과 .prop()

현재 jQuery버전은 2.1.0 등이 릴리즈 되고 있는 상황이지만... 한번 정리를 하고 넘어가고자 글을 남깁니다.


jQuery 1.6 부터 .prop() 메소드가 추가되었습니다.

즉 본래 다른 속성인 attribute와 property를 .attr() 메소드로 가져오던 것을 1.6부터는 구분하기 시작했습니다.


그럼 .attr()과 .prop()는 어떻게 다를까요?

.attr()은 attribute 정보를, .prop()는 property 정보를 가져 옵니다.

즉 먼저 attribute와 property 의 차이를 알아야 하는데요.

명확하게 설명하기가 힘들지만 설며을 하자면 (더 명확한 설명을 아시는분 꼭 이야기 해 주세요)


attrubute는 HTML Element 의 속성들을 뜻하며

property는 자바스크립트의..... (마땅히 번역할 말을 모르겠으니 그냥 프로퍼티로 하겠습니다)

자바스크립트의 프로퍼티를 뜻합니다.


즉 attribute는 HTML Element에서 사용되고, property는 자바스크립트에서 사용되는 정보라고 보시면 됩니다.

이 둘은 비슷한거 같지만 생각보다 굉장히 큰 차이를 가지고 있습니다.


jQuery 사이트에 올라와 있는 차이를 본다면...


Attributes vs. Properties

The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr()method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

For example, selectedIndextagNamenodeNamenodeTypeownerDocumentdefaultChecked, and defaultSelected should be retrieved and set with the .prop() method. Prior to jQuery 1.6, these properties were retrievable with the .attr() method, but this was not within the scope of attr. These do not have corresponding attributes and are only properties.

Concerning boolean attributes, consider a DOM element defined by the HTML markup <input type="checkbox" checked="checked" />, and assume it is in a JavaScript variable named elem:

elem.checkedtrue (Boolean) Will change with checkbox state
$( elem ).prop( "checked" )true (Boolean) Will change with checkbox state
elem.getAttribute( "checked" )"checked" (String) Initial state of the checkbox; does not change
$( elem ).attr( "checked" )  (1.6)"checked" (String) Initial state of the checkbox; does not change
$( elem ).attr( "checked" ) 
(1.6.1+)
"checked" (String) Will change with checkbox state
$( elem ).attr( "checked" )  (pre-1.6)true (Boolean) Changed with checkbox state


According to the W3C forms specification, the checked attribute is a boolean attribute, which means the corresponding property is true if the attribute is present at all—even if, for example, the attribute has no value or is set to empty string value or even "false". This is true of all boolean attributes.

Nevertheless, the most important concept to remember about the checked attribute is that it does not correspond to the checked property. The attribute actually corresponds to the defaultChecked property and should be used only to set theinitial value of the checkbox. The checked attribute value does not change with the state of the checkbox, while the checkedproperty does. Therefore, the cross-browser-compatible way to determine if a checkbox is checked is to use the property:

  • if ( elem.checked )
  • if ( $( elem ).prop( "checked" ) )
  • if ( $( elem ).is( ":checked" ) )

The same is true for other dynamic attributes, such as selected and value.


영어 해석은 힘드니 ㅠㅠ 주요 차이만 짚고 넘어가겠습니다.

확실히 보아야 할 부분은...


$( elem ).attr( "checked" ) (1.6)

$( elem ).attr( "checked" ) (1.6.1+)

$( elem ).prop( "checked" )


요 세가지 입니다.

보시는는 바와같이 .attr()을 사용 할 경우 "checked" 라는 스트링 값 이 넘어옵니다.

하지만 .prop()에선 체크박스의 체크 상태가 true, false 값으로 넘어옵니다.


정리하자면

.attr()을 사용할 경우, 해당 HTML attribute의 값이 모두 String으로 넘어오며, 

.prop()를 사용할 경우 자바스크립트의 프로퍼티값이 넘어오기에 boolean, date, 혹은 function 까지도 넘어 올 수 있습니다.



좀더 확실한 차이를 보자면, onclick, onchange등의 본래 자바스크립트 메소드들의 경우라면

onclick="someFunction()"  이라고 작성되었다고 볼때

.attr() 의 경우 "someFunction()" 이라는 스트링이

.prop() 의 경우onclick  펑션이 넘어오는걸 보실 수 있습니다.

(물론 요런 요상한 코드를 작성할 일이 있을진 모르겠지만...)



이상의 차이가 있으니 앞으로는 .attr()과 .prop()가 사용될 부분을 잘 구분하여 버그로인한 스트레스를 줄이도록 노력합시다~