简体   繁体   中英

jQuery if data attribute add class

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');
        }
      });

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM