커뮤니티

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

Category

교육강좌

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

페이지 정보

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

본문

속성 API

속성은 HTML에서 태그명만으로는 부족한 부가적인 정보라고 할 수 있다. 이 속성을 어떻게 제어하는가 알아보자. 

속성을 제어하는 API는 아래와 같다. 각각의 기능은 이름을 통해서 충분히 유추할 수 있을 것이다.

  • Element.getAttribute(name)
  • Element.setAttribute(name, value)
  • Element.hasAttribute(name);
  • Element.removeAttribute(name);
1
2
3
4
5
6
7
8
9
<a id="target" href="http://opentutorials.org">opentutorials</a>
<script>
var t = document.getElementById('target');
console.log(t.getAttribute('href')); //http://opentutorials.org
t.setAttribute('title', 'opentutorials.org'); // title 속성의 값을 설정한다.
console.log(t.hasAttribute('title')); // true, title 속성의 존재여부를 확인한다.
t.removeAttribute('title'); // title 속성을 제거한다.
console.log(t.hasAttribute('title')); // false, title 속성의 존재여부를 확인한다.
</script>

속성과 프로퍼티

모든 엘리먼트의 (HTML)속성은 (JavaScript 객체의) 속성과 프로퍼티로 제어가 가능하다. 예제를 보자.

1
2
3
4
5
6
7
8
9
10
<p id="target">
Hello world
</p>
<script>
var target = document.getElementById('target');
// attribute 방식
target.setAttribute('class', 'important');
// property 방식
target.className = 'important';
</script>

setAttribute('class', 'important')와 className = 'important'는 같은 결과를 만든다. 하지만 전자는 attribute 방식(속성이라고 부르겠다)이고 후자는 property 방식이다. property 방식은 좀 더 간편하고 속도도 빠르지만 실제 html 속성의 이름과 다른 이름을 갖는 경우가 있다. 그것은 자바스크립트의 이름 규칙 때문이다.

class className
readonly readOnly
rowspan rowSpan
colspan colSpan
usemap userMap
frameborder frameBorder
for htmlFor
maxlength maxLength

심지어 속성과 프로퍼티는 값이 다를수도 있다. 아래 코드를 실행한 결과는 속성과 프로퍼티의 값이 꼭 같은 것은 아니라는 것을 보여준다.

1
2
3
4
5
6
7
8
9
<a id="target" href="./demo1.html">ot</a>
<script>
var target = document.getElementById('target');
console.log('target.href', target.href);
// ./demo1.html
console.log('target.getAttribute("href")', target.getAttribute("href"));
</script>
  • 트위터로 보내기
  • 페이스북으로 보내기
  • 구글플러스로 보내기

답변목록

등록된 답변이 없습니다.