Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch element (element which has click event bind on it) when clicked using Javascript

Imagine this simple html code:

<section onclick="dosomething(event)">
    <div slot="header" class="collapse-header">
      <div class="collapse-image"></div>
      <div class="collapse-text-price-container">
        <div class="collapse-text">სასაჩუქრე ბარათი 200 ლარი – ტანსაცმლის მაღაზია ZURA & SHARK</div>
        <div minprice="1200"></div>
      </div>
      <div class="center-item-container">
        <div class="status success-status">წაღებული</div>
      </div>
      <div class="center-item-container">
        <div class="date-text">10 იან, 2018</div>
      </div>
      <div class="center-item-container">
        <iron-icon class="icon" icon="bog:chevron-down"></iron-icon>
      </div>
    </div>
    <div slot="body" class="collapse-body">
      <div>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old.</div>
    </div>
  </section>

Pay attention to this part of the code : onclick="dosomething(event)". as you see I have many other elements inside outer <section> tag. I also have many sections like that, and on click, I want to get the exact section element which was clicked, How can I do that? event.srcElement sometimes return element inside this section, not the section itself. So what is the solution?

My current solution (which I don't like) is that I take property path or composedPath from event, it's array of elements, and I iterate through it until I find element with tag name section.

like image 928
O. Shekriladze Avatar asked Mar 17 '26 05:03

O. Shekriladze


1 Answers

Try to change function invoking line like that:

<section onclick="dosomething(this, event)">

and then function:

function dosomething(me, e) {
    console.log(me); // returns the section, which was clicked
    console.log(e.target); // returns the element, which was clicked
}
like image 126
Guga Nemsitsveridze Avatar answered Mar 19 '26 18:03

Guga Nemsitsveridze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!