SyntaxStudy
Sign Up
jQuery Intermediate 4 min read

.data() vs .attr()

.data() vs .attr()

.attr() reads/writes the actual HTML attribute. .data() reads from jQuery's cache (initialized from the attribute, but changes do not modify the HTML).

Example
<div id="box" data-count="0"></div>
<script>
// .attr() reads and writes the DOM attribute
$("#box").attr("data-count", 5);
console.log($("#box").attr("data-count")); // "5" (string)

// .data() uses jQuery cache — DOM not updated
$("#box").data("count", 10);
console.log($("#box").data("count"));       // 10 (number)
console.log($("#box").attr("data-count")); // still "5"
</script>
Pro Tip

Use .attr() when you need the value visible in the HTML; .data() for internal JS state.