I have a code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script src="jquery.js"></script><script>
$(function(){
$(".classy").data("read","hi");//Not working .working is$("div").attr("data-read","hi");
});</script>
<style>
.classy[data-read='hello']{background:#000;}.classy[data-read='hi']{background:#fff;}</style>
</head>
<body>
<div class="classy" data-read="hello">a</div>
</body>
</html>
What happening is when document is ready then the data-read attribute of .classy changes to hi.And i have a css style design for .classy[data-read='hi'] but it is not working when i use .data() method to manipulate data-read attribute .it works when i use .attr() method to manipulate data-read.Why?
You misunderstood what
data-xxxis used for. It’s used to populate data inside HTML tags that can later be retrieved using jQuery by using.data().Example:
Output:
When changing that data later on, it won’t change the
data-xxxattribute(s) of the element anymore; this also makes it a bad candidate for conditional CSS treatment.You should use
.addClass(),.toggleClass()and.removeClass()in combination with CSS class selectors to make it work.