Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get ID of parent element on click

I'm trying to display ID of parent UL on LI click. but the alert is displaying value as undefined. Where am I going wrong?

HTML:

<ul id='uiID'>
    <li id='myLi'>A</li>
</ul>

JavaScript

var x = document.getElementById("myLI").parentNode.nodeName;
alert(x.id);
like image 490
Omkar Avatar asked Jan 08 '15 14:01

Omkar


2 Answers

You're not attaching any click event to the element and nodeName in your case returns LI, so that's not wanted. What you want is

document.getElementById("myLI").onclick = function(e){
  alert(e.target.parentNode.id);
}
like image 103
Amit Joki Avatar answered Sep 25 '22 22:09

Amit Joki


You can do something like this :

<ul id='uiID'>
   <li id='myLi' onclick="alert(this.parentNode.id)">A</li>
</ul>
like image 36
potashin Avatar answered Sep 25 '22 22:09

potashin