javascript - HTML How to get id of parent Component? - Stack Overflow

I would like to get the id of the parent tag using javascript. In this example, the parent id of the te

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);
        };
    };
};​

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744305213a4567696.html

相关推荐

  • javascript - HTML How to get id of parent Component? - Stack Overflow

    I would like to get the id of the parent tag using javascript. In this example, the parent id of the te

    9天前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信