PDA

View Full Version : Finding ID of parent tag (i.e. div or span, etc) that surrounds a control or tag



Soteriologist
03-10-2007, 01:48 AM
I'm looking for a way to get the id of a parent tag that a control or tag is nested inside. For example, I want to find the id of the div tag that a hyperlink control is nested inside:



<div id="divTest">
<a id="aTest" href="test.htm">Test</a>
</div>


I know how to get the id of the control itself (this) but is there a way to get the ids of parent tags that it's nested within? And if so, can you get more than just the direct parent above it, or could you possibly step through the whole nest of items? The latter would be most ideal...

Thanx in advance for any replies!

jscheuer1
03-10-2007, 05:46 AM
To get the immediate parent, you can use:


var pid=this.parentNode.id;

However, if there is no id or no parent node, there will be problems. So, you might want to do:


if (this.parentNode&&this.parentNode.id)
var pid=this.parentNode.id;

This also makes 'walking' the nodes looking for id's a bit tricky but, it can be done. It would be helpful to know which parent or id you are looking for, why you are looking for it and, what sorts of things could be there when you go looking.

In one scenario, we could be looking for the parent node with a specified id, this would do that:


function find_pid(el, id){
var p=el;
while(p=p.parentNode;)
if(p.id&&p.id==id)
return p;
return null;
}

You can feed it the child and the id you are looking for. If the child has a parent with the specified id, it will return that parent, otherwise, it will return null.

Veronica
03-10-2007, 02:59 PM
If you want to get everything to the top of the file, you could also try some variation of this.



<html>
<head>
</head>
<body id="body">


<script>
function alertAncestorsUntilID(node, id) {
var parent = node;
while(parent.id != id) {
parent = parent.parentNode;
alert(parent.id);
}
}
</script>

<div id="master1">
<div id="master2">
<a href="#">Master div</a>
<div id="child1"><a href="#">Child div 1</a></div>
<div id="child2"><a href="#">Child div 2</a></div>
<div id="child3"><a href="#">Child div 3</a></div>
<div id="child4"><a href="#">Child div 4</a></div>

</div>
</div>


<script>
alertAncestorsUntilID(document.getElementById("child1"));
</script>


</body>
</html>

Soteriologist
03-12-2007, 09:33 PM
AWESOME!!! Thank you so much you guys!