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

summer_joy·2023년 3월 7일
0
<html>
<body>
  <a id="to_comments" href="#comments">내용</a>
</body>
<script>
  var $link = $('#to_comments');
  alert($link.attr('href'));  // href 속성값 
  alert($link.prop('href'));  // href 프로퍼티값
</script>
</html>
// 결과
.attr() → #to_comment
.prop() → http://example.com/path/to/page#to_comment
<html>
<body>
	<h2>체크박스 예제</h2>
 	<checkbox id="private" type="checkbox" checked />
</body>
<script>
  var $checkbox = $('#private');
  alert($checkbox.attr('checked'));  // checked 속성 값 
  alert($checkbox.prop('checked'));  // checked 프로퍼티 값
</script>
</html>
// 결과
.attr() → "checked"
.prop() → true / false

checked="checked"라는 attribute를 추가할 때
.attr('checked', 'checked'); 또는 .prop('checked', true);
checked="checked"라는 attribute를 제거할 때
.removeAttr('checked'); 또는 .prop('checked', false);

selected="selected"라는 attribute를 추가할 때
.attr('selected', 'selected'); 또는 .prop('selected', true);
checked="checked"라는 attribute를 제거할 때
.removeAttr('selected'); 또는 .prop('selected', false);

자바스크립트 .attr()과 .prop() 차이 정리

.attr() : HTML의 속성을 취급
.prop() : JavaScript프로퍼티를 취급

이 두 개의 메소드는 취급하는 정보가 다름
.attr()는HTML의 속성(attribute)을,
.prop()는 JavaScript의 프로파티(property)를 취급하는 메소드임

profile
💻 Hello world

0개의 댓글