sa.lva.ge sa.lva.ge - 24 days ago 22
HTML Question

javascript onclick get the div id?

Is it possible to get the ids of the 2 div tags on clicking the button, using javascript?

<div id="main">
<div id="content">
</div>
<button onclick="function();">show it</button>
</div>


I have 2 div tags here. The 1st div is in the main div while the content div is inside the main div and the button is inside the main div as well.

Is it possible to get the main and content id of the 2 div tags on clicking the button?

EXPECTED OUTPUT when I press the button:


alert: main
alert: content


Answer

You need to pass the element to the function. Then you can use parentNode to get the DIV that contains the button. From there, you can use querySelector to find the first DIV in the parent.

function showIt(element) {
  var parent = element.parentNode;
  alert(parent.id);
  var content = parent.querySelector("div");
  alert(content.id);
}
<div id="main">
  <div id="content">
  </div>
  <button onclick="showIt(this);">show it</button>
</div>
<div id="main2">
  <div id="content2">
  </div>
  <button onclick="showIt(this);">show it</button>
</div>
<div id="main3">
  <div id="content3">
  </div>
  <button onclick="showIt(this);">show it</button>
</div>

Comments