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');
        }
      });
6
  • 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 Commented Apr 15, 2020 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 …?) Commented Apr 15, 2020 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? <span class="class" id="someID" data-rating="0.0"> Commented Apr 15, 2020 at 12:36
  • Does this answer your question? jQuery .data() does not work, but .attr() does Commented Apr 15, 2020 at 12:44
  • 1
    Important takeaway from this answer: "This is the result of a misunderstanding: data is NOT an accessor for data-* attributes. It's both more and less than that." Commented Apr 15, 2020 at 12:45

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.