简体   繁体   中英

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);

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);
}

You can do something like this :

<ul id='uiID'>
   <li id='myLi' onclick="alert(this.parentNode.id)">A</li>
</ul>

Javascript is case sensitive for most everything:

<li id='myLi'>A</li>
          ^^--- big L, small i

var x = document.getElementById("myLI").parentNode.nodeName;
                                   ^^---big L, big I

Since you're using an undefined ID, getElementById will return null for "no match found". Null has no "parentNode", hence your error.

var id = $(this).parent().attr("id");

console.log(id);

HTML:

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

JavaScript(*you have to just remove ".nodeName" from x)

var x = document.getElementById("myLi").parentNode;
alert(x.id);

You can use closest function to get parent too. Get closest ul to my element.

var el = document.getElementById('myLi');

var r1 = el.closest("ul");

You can use document.getElementById("myLI").parentElement.id

 <p>Example list:</p> <ul id="ul-id"> <li id="myLI">Coffee</li> <li>Tea</li> </ul> <p>Click the button to get the node name of the parent element of the li element in the list.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> function myFunction() { var x = document.getElementById("myLI").parentElement.id; document.getElementById("demo").innerHTML = x; } </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM