View Full Version : Getting the parent id of a clicked linked?

Glass Casket
12-14-2006, 05:22 AM
So I have the following HTML:

<div id = "m0">
<a href = "">
<img src = "plus-small.png" alt = "" />Bank</h3></a>

<li><a href = "javascript: a()">Scotiabank</a> (6)</li>
<li><a href = "javascript: a()">Bank of Montreal</a> (3)</li>
<li><a href = "javascript: a()">CIBC</a> (3)</li>

<li><a href = "javascript: a()">National Bank of Canada</a> (2)</li>
<li><a href = "javascript: a()">Royal Bank</a> (3)</li>
<li><a href = "javascript: a()">TD Bank</a> (6)</li>


I'm trying to make it so when you click on of those links above, an alert window will pop up showing 'm0'. Basically, I'm trying to get the parent id.

I've tried playing with parentNode, but can't seem to get anything going.

Any ideas?


12-14-2006, 08:20 AM
parentNode is the first (the direct) parent. You may extend the reference up to the tree. But you need a start object to perform the up/down tree climbing, and that could be the self reference this.

In your case:

<li><a href="#" onclick="alert(this.parentNode.parentNode.parentNode.id);return false">Scotiabank</a> (6)</li>

this is the self reference, the element <a>
parentNode is the parent <li>
parentNode is the <ul>, the parent of the <li>
parentNode is the <div>, the parent of the <ul>

12-14-2006, 04:10 PM
If you want to assign a function to every link on the page dynamically, you could use the following code:

function assignClickEvent(){
var links = document.links;
for(var i =0; i < links.length; i++)
links[i].onclick = findDivId;

function findDivId(e){
var targ;
if (!e) var e = window.event;
if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;
return false;

window.onload =assignClickEvent;

12-14-2006, 07:15 PM
I figured you might want the closest ancestor with an id.

So here's my attempt too. :)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<title>Find Parent Id</title>
<script type="text/javascript">
function a(o) {
while (o && o.id == "") {
o = o.parentNode;

if (!o.id) {
alert("No parent has an id");
} else {
<div id="m0">
<a href = ""><h3><img src = "plus-small.png" alt = "" />Bank</h3></a>

<li><a href="javascript:;" onclick="a(this);">Scotiabank</a> (6)</li>
<li><a href="javascript:;" onclick="a(this);">Bank of Montreal</a> (3)</li>
<li><a href="javascript:;" onclick="a(this);">CIBC</a> (3)</li>

<li><a href="javascript:;" onclick="a(this);">National Bank of Canada</a> (2)</li>
<li><a href="javascript:;" onclick="a(this);">Royal Bank</a> (3)</li>
<li><a href="javascript:;" onclick="a(this);">TD Bank</a> (6)</li>



Glass Casket
12-17-2006, 06:31 PM
Very nice, everyones input was very useful.