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

Glass Casket
Dec 14th, 2006, 04: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?


Dec 14th, 2006, 07: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>

Dec 14th, 2006, 03: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;

Dec 14th, 2006, 06: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
Dec 17th, 2006, 05:31 PM
Very nice, everyones input was very useful.