简体   繁体   中英

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 

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> 

This should work in all browsers and uses the cleaner .id method.

 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> 

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM