power-girl0-0

[ Element ] jQuery 속성 제어 API 본문

언어/Javascript

[ Element ] jQuery 속성 제어 API

power-girl0-0 2021. 2. 9. 22:00
728x90

 

생활코딩 웹브라우저 javascript를 참고하여 공부하였습니다.

스스로 공부한 것을 정리하고 복습하기 위한 목적으로 작성하였습니다.

( 출처 :  https://opentutorials.org/course/743inf.run/pBzy)


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

jQuery는 좀 더 적은 코드로 동일한 효과를 내는 목적을 갖고 있는데, 이는 실용적인 것을 추구하기 때문이다.


 속성제어 

jQuery 객체의 메소드 중 setAttribute, getAttribute에 대응되는 메소드는 attr이다.

또한, removeAttribute에 대응되는 메소드로는 removeAttr이 있다. 

<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 메소드를 사용한다.

<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이 아래와 같다고 했을 때
    // 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>

attr을 사용한 것은 속성값에 적힌 경로만 출력해주고, prop는 전체 경로를 출력해준다.

또한, 마지막 쪽에서 사용한 attr은 checked에 들을 값을 리턴해주고, prop는 checked라는 속성이 있음을 확인하고 true를 리턴한다.


jQuery를 이용하면 좋은 점은 property 이름으로 어떤 것을 사용하건 올바른 것으로 교정해준다.

이런 것이 라이브러리를 사용하는 의의라고 할수 있겠다.

<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>

 

즉, jQuery에서는 className과 class를 사용하여도 jQuery내부에서는 교정을 해주기 때문에 어떤 것을 사용해도 상관없다.

 

 

 

 

728x90

'언어 > Javascript' 카테고리의 다른 글

[ Node ] Node 객체  (0) 2021.02.10
[ Element ] jQuery 조회 범위 제한  (0) 2021.02.09
[ Element ] 속성 API  (0) 2021.02.09
[ Element ] 조회 API  (0) 2021.02.09
[ Element ] 식별자 API  (0) 2021.02.09
Comments