0

I'm really new to JS and jQuery, but I try adding a class "hide" to an element if it has a data attribute with a specific string. So if "class" hat a data-rating attribute of "0.0", the class "hide" should be added. It doesn't work and I don't know why.

$(document).ready(function() {
         if ($(".class").data('rating') === ('0.0')){
         $(".class").addClass('hide');
        }
      });
Sacha
  • 55
  • 7
  • 1
    Could you show the HTML of the `.class` element. It's likely that the value has been converted to an int or float. You may also need a loop if there are multiple elements with that class – Rory McCrossan Apr 15 '20 at 12:31
  • 2
    (Why do people do stuff like `('0.0')` to begin with? Do they really think text literals would “feel naked” or “freeze to death”, if they don’t blanket them in braces …?) – CBroe Apr 15 '20 at 12:34
  • @CBroe like I said I'm new to JS and jQuery, I just found this line so I used it as it is. you mean the line in the html where that class is used? – Sacha Apr 15 '20 at 12:36
  • Does this answer your question? [jQuery .data() does not work, but .attr() does](https://stackoverflow.com/questions/8707226/jquery-data-does-not-work-but-attr-does) – Heretic Monkey Apr 15 '20 at 12:44
  • It works perfectly. what the problem occuring? – Krupal Panchal Apr 15 '20 at 12:45
  • 1
    Important takeaway from [this answer](https://stackoverflow.com/a/45149219/215552): "This is the result of a misunderstanding: **`data` is NOT an accessor for `data-*` attributes. It's both more and less than that**." – Heretic Monkey Apr 15 '20 at 12:45

1 Answers1

1

jQuery recognises data-rating="0.0" as numeric, so when you call $(".class").data('rating') you get the number 0. Hence, strictly comparing it to any string will fail.

Additionally, your code will not behave as expected if there is more than one element with the given class.

$(".class").each(elem=>{
    const $elem = $(elem);
    if( $elem.data('rating') === 0) {
        $elem.addClass('hide');
    }
});

Or, without jQuery (and therefore immeasurably faster)...

document.querySelectorAll(".class").forEach(elem=>{
    if( parseFloat(elem.getAttribute("data-rating")) === 0) {
        elem.classList.add("hide");
    }
});

Rapid shift back to jQuery, you could also do this:

$(".class[data-rating='0.0']").addClass('hide');

... as a one-liner.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592