skip to Main Content

I have a <ul> with children <li>. All of the <li> are siblings. I need them all to be siblings so that htmx.takeClass(); works to highlight the active item. My layout is like this:

<ul class="list-group list-group-flush"  hx-on:click="if (event.target.classList.contains('list-group-item')) htmx.takeClass(event.target, 'active')">
    <li id="group-1" tabindex="0">Group 1</li>
    <li data-sidebar-group="group-1">Item 1</li>
    <li data-sidebar-group="group-1">Item 2</li>
    <li id="group-2" tabindex="0">Group 2</li>
</ul>

To make a sidebar, I need to select all <li> where the data-sidebar-group matches the id of another <li>. Is there any way to do this in CSS or do I need to resort to JS.

Something like li~li[data-sidebar-group=id] or li[id]~li[data-sidebar-group]. I hope you all understand my question.

2

Answers


  1. You need to resort to JS, there is no way to select in CSS

    Login or Signup to reply.
  2. If you know that that the items that are to become visible on a focus immediately follow the focusable element, as in the given code, then you can use CSS.

    This snippet has put a couple of items after the second focusable one to show the point.

    Selection is done first on all the siblings following the focused one, and then removed the display of any that have another focusable one between it and the focused one.

    *[data-sidebar-group] {
      display: none;
    }
    
    *:focus~*[data-sidebar-group] {
      display: block;
    }
    
    *:focus~*[tabindex]~*[data-sidebar-group] {
      display: none;
    }
    <ul class="list-group list-group-flush" hx-on:click="if (event.target.classList.contains('list-group-item')) htmx.takeClass(event.target, 'active')">
      <li id="group-1" tabindex="0">Group 1</li>
      <li data-sidebar-group="group-1">Item 1</li>
      <li data-sidebar-group="group-1">Item 2</li>
      <li id="group-2" tabindex="0">Group 2</li>
      <li data-sidebar-group="group-2">Item 1</li>
      <li data-sidebar-group="group-2">Item 2</li>
    </ul>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search