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
.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
'Front-End > jQuery' 카테고리의 다른 글
[jQuery] 장바구니 & checkbox (0) | 2020.04.04 |
---|---|
[jQuery] on('click') & click Event (0) | 2019.05.28 |
[jQuery] select option 설정 (0) | 2019.05.27 |
[jQuery] jQuery Plugins 참고 사이트 (0) | 2019.05.23 |
[jQuery] checkbox relation 만들기 (dataset object concept) (0) | 2018.09.09 |
댓글