简体   繁体   English

javascript onclick获取div id?

[英]javascript onclick get the div id?

Is it possible to get the ids of the 2 div tags on clicking the button, using javascript? 是否可以使用javascript点击按钮获取2个div标签的ID?

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

I have 2 div tags here. 我这里有2个div标签。 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. 第一个div位于主div中,而内容div位于主div内,按钮也位于主div内。

Is it possible to get the main and content id of the 2 div tags on clicking the button? 是否可以在单击按钮时获取2 div标签的主要 ID和内容 ID?

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. 然后,您可以使用parentNode获取包含该按钮的DIV From there, you can use querySelector to find the first DIV in the parent. 从那里,您可以使用querySelector查找父级中的第一个DIV

 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. 这应该适用于所有浏览器并使用更干净的.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> 

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/ http://jsfiddle.net/jm5okh69/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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