반응형
속성 API
속성은 HTML에서 태그명만으로는 부족한 부가적인 정보라고 할 수 있다.
속성을 제어하는 API는 아래와 같다. 여기서 name은 class, href, title 등등의 여려 종류로 예를 들 수 하다.
- Element.getAttribute(name) : name의 속성의 값을 가져온다.
- Element.setAttribute(name, value) : name의 value값을 설정한다.
- Element.hasAttribute(name); : name 속성의 존재여부를 true, false로 판단한다.
- Element.removeAttribute(name); : name을 삭제한다.
↓
예시
<a id="jinseok" href="https://k0502s.tistory.com/">블로그</a>
<script>
var t = document.getElementById('jinseok');
console.log(t.getAttribute('href')); // https://k0502s.tistory.com/
t.setAttribute('title', 'k0502s.tistory.com/dome1'); // title 속성의 값을 k0502s.tistory.com/dome1 추가 설정한다.
console.log(t.hasAttribute('title')); // true, title 속성의 존재여부를 확인한다.
t.removeAttribute('titlef'); // title 속성을 제거한다.
</script>
속성과 프로퍼티
모든 엘리먼트의 (HTML)속성은 (JavaScript 객체의) 속성과 프로퍼티로 제어가 가능하다
<p id="jinseok">
Hello world
</p>
<script>
var jinseok = document.getElementById('jinseok');
// attribute 방식
jinseok.setAttribute('class', 'kim');
// property 방식
jinseok.className = 'kim';
</script>
- setAttribute('class', 'kim')와 className = 'kim'는 같은 결과를 만든다.
- 하지만 전자는 attribute 방식(속성이라고 부르겠다)이고 후자는 property 방식이다.
- property 방식은 좀 더 간편하고 속도도 빠르지만 실제 html 속성의 이름과 다른 이름을 갖는 경우가 있다. 그것은 자바스크립트의 이름 규칙 때문이다.
class | className |
readonly | readOnly |
rowspan | rowSpan |
colspan | colSpan |
usemap | userMap |
frameborder | frameBorder |
for | htmlFor |
maxlength | maxLength |
심지어 속성과 프로퍼티는 값이 다를수도 있다. 코드를 실행한 결과는 속성과 프로퍼티의 값이 꼭 같은 것은 아니라는 것을 보여준다.
<a id="jinseok" href="./demo1.html">ot</a>
<script>
//결과 : 현재 웹페이지가 http://localhost/webjs/Element/attribute_api/demo3.html 일 때
var target = document.getElementById('jinseok');
//결과 : http://localhost/webjs/Element/attribute_api/demo1.html
console.log('jinseok.href', jinseok.href);
//결과 : ./demo1.html
console.log('jinseok.getAttribute("href")', jinseokt.getAttribute("href"));
</script>
반응형
'프로그래밍 개발 > JS 웹' 카테고리의 다른 글
Javascript Node 객체 (0) | 2020.11.20 |
---|---|
javascript Element 객체 - jQuery 속성 제어 API (0) | 2020.11.19 |
javascript Element 객체 - 조회 API (0) | 2020.11.19 |
javascript Element 객체 - 식별자 API (0) | 2020.11.19 |
javascript Element 객체 (0) | 2020.11.19 |
댓글