프론트엔드/Javascript
[프론트엔드] HTML 데이터 속성 dataset
jinwanseo
2021. 2. 23. 16:13
728x90
FrontEnd HTML Element Attribute - Dataset

HTML 데이터 속성은 엘리먼트 내
attribute명으로 data- + 키이름 으로 사용
Javascript 에서 해당 데이터의 속성을
접근하기 위해서는 엘리먼트명.dataset.키이름
※일반적인 객체와 같이 dataset[키이름] 으로는 접근 불가!
[샘플 예제]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dataset Example</title>
<style>
body {
margin : 50px;
}
</style>
</head>
<body>
<input type="text" id="textBox1">
<input type="text" id="textBox2">
<input type="button" value="클릭!" data-name="메모를메모하다" data-title="스크립트예제"/>
<script>
document.querySelector('input[type="button"]').addEventListener('click',e=>{
document.querySelector('#textBox1').value = e.target.dataset.name;
document.querySelector('#textBox2').value = e.target.dataset.title;
});
</script>
</body>
</html>
[결과 출력]

728x90