커뮤니티

고용노동부, 산업인력공단과 함께하는 강원도 유일한 기업중심 IT전문교육기관 ICT융합캠퍼스만의 특별한교육입니다.
공인 IT숙련기술인의 다양한 접근방법으로 전문가다운 실무교육을 받을 수 있습니다.

Category

교육강좌

클라이언트 웹브라우저 자바스크립트 - jQuery 속성 제어 API

페이지 정보

작성자 관리자 댓글 0건 조회 2,150회 작성일 20-07-20 14:25

본문

jQuery 속성 제어 API

지금까지 살펴본 Element의 API에 해당하는 기능을 jQuery에서는 어떻게 구사하는가를 알아보자. 

속성제어

jQuery 객체의 메소드 중 setAttribute, getAttribute에 대응되는 메소드는 attr이다. 또한 removeAttribute에 대응되는 메소드로는 removeAttr이 있다. 

1
2
3
4
5
6
7
8
<a id="target" href="http://opentutorials.org">opentutorials</a>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
var t = $('#target');
console.log(t.attr('href')); //http://opentutorials.org
t.attr('title', 'opentutorials.org'); // title 속성의 값을 설정한다.
t.removeAttr('title'); // title 속성을 제거한다.
</script>

attribute와 property

DOM과 마찬가지로 jQuery도 속성(attribute)과 프로퍼티를 구분한다. 속성은 attr, 프로퍼티는 prop 메소드를 사용한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<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이 아래와 같다고 했을 때
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>

jQuery를 이용하면 프로퍼티의 이름으로 어떤 것을 사용하건 올바른 것으로 교정해준다. 이런 것이 라이브러리를 사용하는 의의라고 할수 있겠다.

1
2
3
4
5
6
7
<div id="t1">opentutorials</div>
<div id="t2">opentutorials</div>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$('#t1').prop('className', 'important');
$('#t2').prop('class', 'current');
</script>
  • 트위터로 보내기
  • 페이스북으로 보내기
  • 구글플러스로 보내기

답변목록

등록된 답변이 없습니다.