Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Select Sibling of an Event target JavaScript

I have the following simplified html

<div class="wrapper">
  <div class="content">
    <div class="item">
      <h1>Item 1</h1>
      <div class="effect"></div>
      <button class="btn">show</div>
    </div>
    <div class="item">
      <h1>Item 2</h1>
      <div class="effect"></div>
      <button class="btn">show</div>
    </div>
    <!-- and so on -->
  </div>
</div>

all buttons have click event listener. how to select div.effect using event.target

is there something like

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

document.querySelector(event.target + " + .effect")
Note

I can’t use other method than event.target so obvious work arounds like adding some custom call for each button, or adding id is not what I’m looking for

>Solution :

You can use the previousElementSibling property that has a target to get the sibling.

var effectDiv = event.target.previousElementSibling;
if (effectDiv.classList.contains('effect')) {
  // do something with effectDiv
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading