-2

On one page, several Collapsibles can occur! I would like to now, if a link is activated. Get the ProductItem in which the link was activated.

I have tried it with getElementsByClass but get a complete Node-List which doesn't help me! Because there can be several collapsibles on one page

<div class="collapsible">
    <div class="collapsible__item collapsible__item--active">
        <div class="collapsible__body" style="">
            <section id="c395" class="frame centered frame-type-flux_productlistitem frame-layout-0">
                <section>
                    <div class="products">
                        <ul class="products__list">
                            <li class="products__item">
                              <p><a>Link</a></p>
                            </li>
                            <li class="products__item">
                               <p><a>Link</a></p>
                            </li>
                        </ul>
                    </div>
                </section>
            </section>
        </div>
    </div>
</div>
H.Solo
  • 79
  • 1
  • 11
  • 3
    Can you share the JavaScript you have as well? It's hard to tell just from that markup what you're trying to do and what you've tried. – darth_mall Jul 29 '19 at 20:41
  • I tried a few things and it didn't work out! I was hoping someone could give me a hint! – H.Solo Jul 29 '19 at 21:51

1 Answers1

1

Simply use event delegation, where you set up an event handler on a high level DOM element and then investigate the instigating element through the event reference:

// Set up the event on a high-level element
document.querySelector(".collapsible").addEventListener("click", function(evt){
  // Get information about the element that originated the event
  console.log("The event originated with: ", evt.target);
  console.log("The product is: ", evt.target.closest("li").classList.toString());
});
<div class="collapsible">
    <div class="collapsible__item collapsible__item--active">
        <div class="collapsible__body" style="">
            <section id="c395" class="frame centered frame-type-flux_productlistitem frame-layout-0">
                <section>
                    <div class="products">
                        <ul class="products__list">
                            <li class="products__item1">
                              <p><a>Link 1</a></p>
                            </li>
                            <li class="products__item2">
                               <p><a>Link 2</a></p>
                            </li>
                        </ul>
                    </div>
                </section>
            </section>
        </div>
    </div>
</div>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71