Home > Mobile >  Can I use variables or regex for selectors in CSS?
Can I use variables or regex for selectors in CSS?

Time:11-19

Hi,

I have this markup:

<div data-users="room2">
 <span data-room="room1,room2,room3">john</span>
 <span data-room="room1">george</span>
 <span data-room="room2">jane</span>
</div>

I want only users that have the same room data as the div parent so I wrote this css:

span { display: none; }
[data-users="room2"] [data-room*="room2"] { display: block; }

fiddle: https://jsfiddle.net/ehpt9f5z/2/

However, since the data in the div parent can change to any room number I need a variable there so the CSS selector will always match the room data from the child with its parent, something like this:

[data-users=$1] [data-room*=$1] { display: block; }

Is it even possible with pure css?

Thank you.

CodePudding user response:

This is not accomplishable with CSS alone, since there is no CSS parent selector.

A JavaScript solution would be to loop through each div which has the data-users attribute, then loop through each child of the div and show the ones whose data-room attribute contains the data-users attribute value.

const divs = document.querySelectorAll('div[data-users]')

divs.forEach(e => [...e.children].forEach(f => {
  if(f.dataset.room.split(',').includes(e.dataset.users)){
    f.style.display = "block"
  }
}))
span { display: none; }
<div data-users="room2">
 <span data-room="room1,room2,room3">john</span>
 <span data-room="room1">george</span>
 <span data-room="room2">jane</span>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related