Sailo1
Sailo1

Reputation: 57

How to get one div id when it is inside another div

I have two rectangles. The bigger one is "house" and it contains the smaller one "room". I would like to get alert with div id once I click on any of this rectangles. But when I click on green rectangle I need to get "room" and on red then I need to get "house". Here is the code in the https://jsfiddle.net/pr2501/6a4qwdgx/17/ How to make it work?

Html:

<div id="house"  onClick="reply_click(this.id)"   style="border: 2px solid red; height:50px;width:50px;padding:15px;">        
        <div id="room"  onClick="reply_click(this.id)"  style="border: 2px solid green; height:25px;width:25px;">           
        </div>
    </div>

and JS:

function reply_click(clicked_id)
  {
      alert(clicked_id);
  }

Upvotes: 1

Views: 85

Answers (2)

Ori Drori
Ori Drori

Reputation: 191976

Add a single event listener to to #house, and get the id from the event's target (e.target):

document.querySelector('#house')
  .addEventListener('click', e => {
    console.log(e.target.id);
  });
<div id="house" style="border: 2px solid red; height:50px;width:50px;padding:15px;">
  <div id="room" style="border: 2px solid green; height:25px;width:25px;">
  </div>
</div>

If you want to use an inline function, set it only on the outer div, and pass event as param:

function reply_click(e) {
  console.log(e.target.id)
}
<div id="house" onClick="reply_click(event)" style="border: 2px solid red; height:50px;width:50px;padding:15px;">
  <div id="room" style="border: 2px solid green; height:25px;width:25px;">
  </div>
</div>

Upvotes: 2

Addis
Addis

Reputation: 2530

The green rectangle is also inside the red rectangle. So when you click inside the inner rectangle the outer rectangle also listens to the event. So, you need to stop the event propagation.

  function reply_click(clicked_id)
  {
      alert(clicked_id);
      event.stopPropagation();
  }

Upvotes: 1

Related Questions