1/* html */
2<a data-id="123">link</a>
3
4/* js */
5$(this).attr("data-id") // returns string "123"
6
7$(this).data("id") // returns number 123 (jQuery >= 1.4.3 only)
1/* html */
2<a data-number="123">link</a>
3
4/* js */
5$(this).attr("data-number") // returns string "123"
6
7$(this).data("number") // returns number 123 (jQuery >= 1.4.3 only)
1alert($('#outer').html()); // alerts <div id="mydiv" data-myval="10"> </div>
2var a = $('#mydiv').data('myval'); //getter
3$('#mydiv').attr("data-myval","20"); //setter
4alert($('#outer').html()); //alerts <div id="mydiv" data-myval="20"> </div>
1data attribute in jquery
2
3For setting attribute data to the element
4Html
5<p id="assign">Assigning data attribute</p>
6jquery
7$("#assign").data("title","firstparagraph");
8
9Output:
10<p id="assign" data-title="firstparagraph">Assigning data attribute</p>
11
12For getting attribute data from the element
13Html
14<p id="assign" data-title="firstparagraph">Assigning data attribute</p>
15jquery
16console.log($("#assign").data("title"));
17console.log($("#assign").data());
18
19Output:
20firstparagraph
21{ title: firstparagraph }