dataset 05.웹페이지 시작하기

sohyun·2022년 5월 16일
0

웹페이지 시작하기

목록 보기
5/10

HTML data 속성 사용하기

data-*

  • 특정데이터를 DOM요소에 저장해두기 위해
  • 브라우저는 데이터 속성에 어떠한 행동도 관여하지 않기 때문에
    개발자는 요소에 특정한 데이터를 저장하고 싶은경우 자유롭게 사용가능
  • 데이터속성 조작은 자바스크립트에서 dataset객체를 통해 조작가능
<button type="button" class="mybtn" data-name="javascript" data-age="20">javasscript;20</button>
<button type="button" class="mybtn" data-name="vanila" data-age="15">vanila;15</button>
<h1 id="console"></h1>

HTML data-* 제어하기 : dataset

dataset

  • HTML5부터는 HTML태그 안에 data-* 형식의 속성을 개발자가 필요한 경우 임의로 정의 가능
  • 이 속성을 사용하여 HTML태그 안에서 JS에서 활용할 수 있는 정보를 포함시킬 수 있다.
  • 이 속성들은 js로 가져온 HTML요소 객체의 dataset프로퍼티 하위에 포함된다
    <script>
        const mybtn = document.querySelectorAll(".mybtn");

        for (btn of mybtn) {
            btn.addEventListener("click", e => {
                //html태그에 존재하지 않는 속성을 JS로 추가하는 것은 가능
                //-> data-helloworld="안녕하세요"
                e.currentTarget.dataset.helloworld = "안녕하세요";
                const name = e.currentTarget.dataset.name;
                const age = e.currentTarget.dataset.age;
                document.getElementById("console").innerHTML = "이름:" + name + ",나이:" + age;

                //HTML태그에 없는 속성을 출력하거나 다른변수에 복사하는 경우 undesfined
                consoel.log(e.currentTarget.dataset.test);
            })
        }

    </script>
profile
냠소현 개발일지

0개의 댓글