Reputation: 2623
Hi I have a drop down menu by using LI & UL tag .
Eg.
<ul>
<li><a href="#">Parent 1</a>
<ul>
<li id = "Child 1"><a href="#">Child 1</a></li>
<li id = "Child 2"><a href="#">Child 2</a></li>
</ul>
</li>
<li><a href="#">Parent 2</a>
<ul>
<li id = "Child 3"><a href="#">Child 3</a></li>
<li id = "Child 4"><a href="#">Child 4</a></li>
</ul>
</li>
</ul>
Now my problem is when I click on Child 1 then in the resultant div should display Parent 1: Child 1 . How can I achieve this?
Thank You.
Upvotes: 0
Views: 5211
Reputation: 116110
<ul>
<li><a href="#">Parent 1</a>
<ul>
<li id = "Child 1"><a href="#" onclick="alert(this.parentNode.parentNode.parentNode.firstChild.innerText + ':' + this.innerText)">Child 1</a></li>
<li id = "Child 2"><a href="#">Child 2</a></li>
</ul>
</li>
<li><a href="#">Parent 2</a>
<ul>
<li id = "Child 3"><a href="#">Child 3</a></li>
<li id = "Child 4"><a href="#">Child 4</a></li>
</ul>
</li>
</ul>
The reason for this is that you click the link. So you have to go up throught the ul, to the li, and then get its first client, which is the link containing Parent1.
Upvotes: 0
Reputation: 13756
this.parentElement().getAttribute('id');
this will do the trick
where this
is clicked link
so if the method is
function linkClick(obj)
{
alert(obj.parentElement().getAttribute('id') + ':' + obj.innerHTML);
}
all you need to do is attach onclick event to your link
<a onclick="linkClick(this); return false;" href="#">Child 1</a>
Upvotes: 2