CSS Selector: use attr() as value

Viewed 35

i'm trying to select a item dynamically with the help of css attr(). In this case I want to show only elements which contains the attribute "data-color" in the attribute "data-media".

I'm planning to do something like this:

HTML:

<div class="item" data-media="item_GG_Front.jpg" data-color="_CDMR_">don't show item</div>
<div class="item" data-media="item_CDMR_Front.jpg" data-color="_CDMR_">show item</div>

CSS:

.item {
   display: none;
}
.item[data-media*="attr('data-color')"] {
   display: block;
}

Is this possible with CSS? Because I don't want to declare all color options. I must declare this very flexible, because the attribute "data-color" changes dynamically with Javascript.

Thanks a lot!

1 Answers

You can find a solution in javascript at the bottom of your html :

document.querySelectorAll('.item[data-media][data-color]').forEach(e => {
    if(e.getAttribute('data-media').includes(e.getAttribute('data-color'))) {
        e.style.display = 'block';
    }
});

You just have to let the css :

.item {
   display: none;
}
Related