1

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.com" id = "sofsite">stackoverflow</a>.
 </body>
Jasper van den Bosch
  • 3,169
  • 4
  • 32
  • 55
RAVI
  • 3,143
  • 4
  • 25
  • 38
  • What if the text "stackoverflow" appears many times on the page, inside of components with differing ID's? – calebds May 01 '12 at 15:43

2 Answers2

4
var parentid = textnode.parentNode.id;

See docs for parentNode.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

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.net/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);
        };
    };
};​
GillesC
  • 10,647
  • 3
  • 40
  • 55