hyperscript

How to find an element relative to the clicked element


I'm trying to use Hyperscript to find the nearest parent element with the class .foo when a user clicks on any element inside a <div>. Here's what I have so far:

<div _="on click log target's closest .foo">
  <details class="foo"><summary>AAA</summary>aaa</details>
  <details class="foo"><summary>BBB</summary>bbb</details>
</div>

My other failed attempts:

_ = "on click log target's closest .foo"
_ = "on click log target's closest <details/>"
_ = "on click log the closest .foo from target"
_ = "on click log the closest .foo to the target"

How can I correctly find and log the nearest .foo parent relative to the clicked element using Hyperscript?


Solution

  • You can try the below solution:

    <div _="on click log target.closest('.foo')">
      <details class="foo"><summary>AAA</summary>aaa</details>
      <details class="foo"><summary>BBB</summary>bbb</details>
    </div>
    

    target.closest('.foo') uses the JavaScript closest() method to find the nearest ancestor element with the class .foo relative to the clicked element.