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);
};
};
};
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744305213a4567696.html
评论列表(0条)