Javascript onclick get div id?

Is it possible to get 2 div tag ids on button click using javascript?

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

      

I have 2 div tags here. The first div is inside the main div, while the content of the div is inside the main div, and the button is also inside the main div.

Is it possible to get the main and content icon from two div tags on button click?

EXPECTED OUTPUT when I press the button:

alert: main
alert: content

      

+3


source to share


3 answers


You need to pass the element to the function. Then you can use parentNode

to get DIV

which contains the button. From there you can use querySelector

to find the first one 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>
      

Run codeHide result


+4


source


This should work in all browsers and use a cleaner method .id

.



var button = document.getElementById('button');

button.onclick = getIDs;

function getIDs(){
 var id,divs = document.getElementsByTagName('div');
    for (var i = 0; i < divs.length; i++) {        
         id = divs[i].id //  .id is a method 
        alert(id);
    }
}
      

<div id="main">
    <div id="content"></div>
    <button id="button">show it</button>
</div>
      

Run codeHide result


+1


source


document.getElementById('button').onclick = function () {
    var divs = document.querySelectorAll('div');
    for (var i = 0; i < divs.length; i++) {
        var id = divs[i].getAttribute('id');
        alert(id);
    }
};

      

http://jsfiddle.net/jm5okh69/1/

0


source







All Articles