Omkar
Omkar

Reputation: 303

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

Upvotes: 12

Views: 53761

Answers (7)

ShriP
ShriP

Reputation: 128

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>

Upvotes: 0

benzo
benzo

Reputation: 431

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

Upvotes: 0

user13441281
user13441281

Reputation:

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

Upvotes: 0

Omair
Omair

Reputation: 51

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

console.log(id);

Upvotes: 1

Marc B
Marc B

Reputation: 360562

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.

Upvotes: 2

Amit Joki
Amit Joki

Reputation: 59232

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

Upvotes: 21

potashin
potashin

Reputation: 44581

You can do something like this :

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

Upvotes: 10

Related Questions