简体   繁体   中英

How to compare data attributes of parent and child?

I'm trying to compare the data attributes of a child div to its parent div and if they do not match then hide the child element. I want to be able to compare for each instance of the parent child relationship. .test is the parent and .event is the child. Here is what I have.

    if ($(".event").data("campaign-id") != $(".event").parent().data("campaign-id")) {
        $(".event").hide();
    }

data as getter returns specified datum of the first selected element in the set. Your script hides the all .event elements when the first .event element's campaign-id datum matches with it's parent campaign-id datum. You could use the .filter() method:

$(".event").filter(function() {
   return $(this).data("campaign-id") !== $(this.parentNode).data("campaign-id");
}).hide();

If you are getting data-campaign-id attributes and not the data stored by jQuery, another option is:

[].forEach.call(document.querySelectorAll('.event'), function(el) {
    var c = el.getAttribute('data-campaign-id'),
        p = el.parentNode.getAttribute('data-campaign-id');
    if ( c !== p ) {
        el.style.display = 'none';
    }
});

You can use .each() for this task:

 $(".event").each(function(){
     if($(this).data("campaign-id") != $(this).parent().data("campaign-id"))    
     {
          $(this).hide();
     }
 });

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