Lumnezia
Lumnezia

Reputation: 796

Modify custom HTML-Attribute with jquery does not affect CSS

I have an Element with the custom attribute data-badge="1" that looks like this:

<div id="badge" data-badge="1">
  <span></span>
</div>

Now I have some css styling the :after element of this divs chils-span. But as soon as the attribute data-badge is zero, I want to hide the :after element. So naturally I added this to the CSS

#badge span:after {
    display: block;
    content: " ";
    ...
}

#badge[data-badge="0"] span:after {
   display: none;
}

This works quite well if I load the page, but as soon as I change the "data-badge" attribute using jquery, the element will no longer be hidden. What can cause this?

Thank you for your help

EDIT: Due to a request, here is the Jquery-Code aswell:

$(".button").click(function(){
   $("#badge").data("data-badge","0");
});

(Of course there is way more jquery-code but this is literally the only part, that has anything to do with this attribute. And the problem occurs also, if the data-badge attribute is changed via jquery in the browser-console)

Upvotes: 2

Views: 232

Answers (1)

xec
xec

Reputation: 18034

It seems to work fine as is;

$(".button").click(function(){
   $("#badge").attr("data-badge","0");
});
#badge span:after {
    display: block;
    content: "text";
}
#badge[data-badge="0"] span:after {
    display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="badge" data-badge="1">
  <span></span>
</div>
<button class="button">click me</button>

There must be something else interfering


Edit As commented, it seems the issue was the difference between .data() and .attr() in jQuery. To summarize:

  1. .data() will read the value from data-* attributes, but writing will only update internally (will not apply to the the DOM)
  2. .attr("data-*") will both read and write directly to the DOM attribute, which will affect what css can be applied to it

Upvotes: 4

Related Questions