Web API : DOM 제어하기 -Element API

BakJiYeon·2022년 2월 1일
0

WEB관련 개념, 이론

목록 보기
2/4

Element객체

식별자 API

  • element.tagName ; read only
  • element.id
  • element.className
  • element.classList
    : element의 class 속성의 컬렉션인 활성 DOMTokenList를 반환하는 읽기 전용 property이다.
    add, remove, toggle등의 메서드가 있다.

조회 API

document와 Element둘 다 getElementsBy~메서드를 갖는다.
특정 element하위에서 조회하고 싶을 때는 element의 property를 쓰자.
document.getElementsBy~
element.getElementsBy~

속성 API

  • element.getAttribute(name)
  • element.setAttribute(name, value)
  • element.hasAttribute(name)
  • element.removeAttribute(name)
    *Attribute 관련 메서드

Element의 property / attribute 메서드

모든 Element의 HTML attribute(속성)은 Javascript 객체의 attribute 관련 메서드와, property로 제어가 가능하다.

HTML attribute이름과 Javascript에서의 property이름이 일치하지 않는 경우가 있다. 대표적으로 class, className

또한, Javascript Element의 property로 접근하면 HTML에서 작성한 값과 다를 수도 있다.

 <a id="test" href="./test.html">This is a test</a>

Element의 property로 접근

 const test = document.querySelector("#test");
 console.log(test.href) 
 // http://localhost:5500/src/test.html와 같은 절대 경로를 출력한다.

getAttribute메서드로 접근

console.log(test.getAttribute("href"))
// HTML에서 작성한 대로 상대경로를 출력한다.

References
https://developer.mozilla.org/ko/docs/Web/API/Element
https://opentutorials.org/course/1375/6683
https://developer.mozilla.org/ko/docs/Web/API/Element/classList
https://developer.mozilla.org/ko/docs/Web/API/Element/getAttribute

profile
no tomorrow without joy

0개의 댓글