[HTML] 데이터셋 (dataset)

흑우·2023년 8월 12일

HTML

목록 보기
3/3

서론

오늘은 HTML5에서 새롭게 추가된 Dataset에 대해서 알아보겠습니다.
Dataset은 HTML에 추가의 커스텀 속성을 표시하는 데 표준화된 방법을 제공하기 위해 제안되었습니다.
"data-*" 어트리뷰트로 표기하며, HTML5 표준 속성처럼 접근할 수 있습니다.

HTML dataset 문법

<article
  id="electric-cars"
  data-columns="3"
  data-index-number="12314"
  data-parent="cars"></article>

자바스크립트로 데이터셋 접근

const article = document.querySelector("#electric-cars");
// const article = document.getElementById("electric-cars")

article.dataset.columns; // "3"
article.dataset.indexNumber; // "12314"
article.dataset.parent; // "cars"

CSS로 데이터셋 접근하기

article[data-columns="3"] {
  width: 400px;
}
article[data-columns="4"] {
  width: 600px;
}
  • querySelector(), querySelectorAll() 메서드를 사용할 때도 데이터셋 속성을 사용해 노드를 선택할 수 있습니다.

주의할 점

  • 인터넷 익스플로러 10까지는 지원되지 않습니다. 11이상부터 지원하며, 인터넷 익스플로러 10 이하 호환성 유지가 필요한 경우, 사용하면 안되며, 데이터셋 속성에 접근하려면 getAttribute() 로 접근해야 합니다.

Reference

profile
흑우 모르는 흑우 없제~

0개의 댓글