admin管理员组文章数量:1401499
I would like to get the id of the parent tag using javascript. In this example, the parent id of the text "stackoverflow" is "sofsite" and the parent id of "This" is "sofbody".
<body id = 'sofbody'>
This is <a href = "www.stackoverflow" id = "sofsite">stackoverflow</a>.
</body>
I would like to get the id of the parent tag using javascript. In this example, the parent id of the text "stackoverflow" is "sofsite" and the parent id of "This" is "sofbody".
<body id = 'sofbody'>
This is <a href = "www.stackoverflow." id = "sofsite">stackoverflow</a>.
</body>
Share
Improve this question
edited May 2, 2012 at 8:17
Jasper van den Bosch
3,2185 gold badges33 silver badges56 bronze badges
asked May 1, 2012 at 15:39
RAVIRAVI
3,1534 gold badges27 silver badges38 bronze badges
1
- What if the text "stackoverflow" appears many times on the page, inside of ponents with differing ID's? – calebds Commented May 1, 2012 at 15:43
2 Answers
Reset to default 5var parentid = textnode.parentNode.id;
See docs for parentNode
.
All you need to do is access the clicked element parentNode property and keep going up until you find one that match the id you are after.
Here is a little fiddle http://jsfiddle/8aPnq/
var parent, elem, id = 'sofbody',
a = document.getElementById('sofsite'),
found = false;
a.onclick = function(ev) {
ev.preventDefault();
while (!found) {
parent = parent ? parent.parentNode : ev.target.parentNode;
if (parent.id === id) {
elem = parent;
found = true;
console.log(elem);
};
};
};
本文标签: javascriptHTML How to get id of parent ComponentStack Overflow
版权声明:本文标题:javascript - HTML How to get id of parent Component? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744305213a2599777.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论