본문 바로가기
Front-End/jQuery

[jQuery] data()

by 김뚱 2019. 5. 28.

data()는 HTML element에 메타 데이터 정보를 읽는 역할을 하는 함수이다.

 

data 저장

var tar = document.getElementByTagName('h2')[0]; //$('h2')[0]

//방법1
tar.setAttribute('data-color', 'red'); //<h2 data-color="red">test</h2>

//방법2
tar.dataset.color = 'blue'; //<h2 data-color="red">test</h2>

//결과 확인
console.log(tar.outerHTML);

 

data 읽기

var tar = document.getElementByTagName('h2')[0];

//방법1
var color = tar.getAttribute('data-color'); //red

//방법2
var color = $(tar).data('color'); //red

//결과 확인
console.log(tar.outerHTML);

 

data 지우기

var tar = document.getElementByTagName('h2')[0];

tar.removeAttribute('data-color');

//undefined

 

Reference

http://api.jquery.com/data/

 

.data() | jQuery API Documentation

Description: Return arbitrary data associated with the first element in the jQuery collection, as set by data() or by an HTML5 data-* attribute. The .data() method allows us to read data previously associated with DOM elements. We can retrieve several dist

api.jquery.com

http://api.jquery.com/removeData/

 

.removeData() | jQuery API Documentation

Description: Remove a previously-stored piece of data. The .removeData() method allows us to remove values that were previously set using .data(). When called with the name of a key, .removeData() deletes that particular value. When called with no argument

api.jquery.com

https://johnresig.com/blog/html-5-data-attributes/

 

John Resig - HTML 5 data- Attributes

A new feature being introduced in HTML 5 is the addition of custom data attributes. This is a, seemingly, bizarre addition to the specification – but actually provides a number of useful benefits. Simply, the specification for custom data attributes states

johnresig.com

 

728x90
반응형

댓글