Reputation: 303
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
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
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
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
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
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
Reputation: 44581
You can do something like this :
<ul id='uiID'>
<li id='myLi' onclick="alert(this.parentNode.id)">A</li>
</ul>
Upvotes: 10