본문 바로가기
프로그래밍 개발/JS 웹

javascript Element 객체 - jQuery 속성 제어 API

by Jinseok Kim 2020. 11. 19.
반응형

 

jQuery 속성 제어 API

 

 

 Element의 API에 해당하는 기능을 jQuery에서는 어떻게 구사 가능하다.

 

 

 

 

 

속성제어

 

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

 

<a id="jinseok" href="https://k0502s.tistory.com/">블로그</a>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
var t = $('#jinseok');

console.log(t.attr('href')); //https://k0502s.tistory.com/

t.attr('title', 'kim'); // title 속성의 값을 추가 설정한다.

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

 

 

 

 

 

 

 

attribute와 property

 

DOM과 마찬가지로 jQuery도 속성(attribute)프로퍼티를 구분한다.

속성은 attr, 프로퍼티는 prop 메소드를 사용한다.

 

<a id="t1" href="./demo.html">URL</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>

 

 

 

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

<div id="t1">jin</div>
<div id="t2">seok</div>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$('#t1').prop('className', 'kim'); 
$('#t2').prop('class', 'kim');  
</script>

t1, t2 둘다 class의 값이 추가 된 것을 확인 할 수 있다.

 

반응형

댓글