data attribute는 특정한 데이터를 DOM 요소에 저장해두기 위해서 사용된다
<input type="text" value="hello" data-value="001" id="username">
보통 value값처럼 target.value로 접근하지 않고 자신이 설정한 값으로 자유롭게 접근이 가능하다
사용자 지정 데이터 특성(custom data attributes)이라는 클래스를 만들어 낼 수 있다는 장점이 있다
<div>
id="electriccars"
data-columns="3"
data-index-number="1234"
data-parent="cars">
...
</div>
이렇게 data-xxxx 를 이용해서 특정한 속성을 만들어낼 수 있다
<input type="text" data-value="001" data-code="c03" data-name="num1" id="username">
이렇게 하나의 input 태그 안에 여러개의 속성을 넣을 수 있다.
<div class="color-option" style="background-color: red" data-color="green"></div>
위의 예시처럼 data-color을 이용해서 javascript로 접근할 수 있다
어떤 color가 선택되었을지를 js에서 알아내기 위해서 data attribute를 이용한다
console.log(event.target);
console.log(event.target.dataset['color']);
이렇게 data-color라는 data attribute를 이용해서 red 이라는 속성값을 얻어낼 수 있다는 것을 콘솔창으로 확인한다
const colorOption = Array.from(document.getElementsByClassName('color-option'));
function onColorClick(event) {
context.strokeStyle = event.target.dataset['color'];
}
colorOption.forEach(color => color.addEventListener('click', onColorClick));
그리고 최종적으로 이를 통해 html DOM 요소를 접근해서 바꿀 수 있다
민감한 데이터는 데이터 속성으로 넣지 않는 것이 좋다
접근 보조 기술이 접근할 수 없기 때문이다
또한 인터넷 익스플로러(그놈의 익스플로러)는 표준을 지원하지만, 이전 버전들은 dataset을 지원하지 않는다