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
Add a ment  | 

2 Answers 2

Reset to default 5
var 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