[英]Get ID of parent element on click
I'm trying to display ID of parent UL
on LI
click.我正在尝试在
LI
单击时显示父UL
ID。 but the alert is displaying value as undefined.但警报显示值未定义。 Where am I going wrong?
我哪里错了?
HTML: HTML:
<ul id='uiID'>
<li id='myLi'>A</li>
</ul>
JavaScript 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.您没有将任何点击事件附加到元素和
nodeName
在您的情况下返回LI
,所以这是不想要的。 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: Javascript 对大多数情况都区分大小写:
<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".由于您使用的是未定义的 ID,因此 getElementById 将为“未找到匹配项”返回 null。 Null has no "parentNode", hence your error.
Null 没有“parentNode”,因此您的错误。
var id = $(this).parent().attr("id");
console.log(id);
HTML: HTML:
<ul id='uiID'>
<li id='myLi'>A</li>
</ul>
JavaScript(*you have to just remove ".nodeName" from x) JavaScript(*你只需要从 x 中删除“.nodeName”)
var x = document.getElementById("myLi").parentNode;
alert(x.id);
You can use closest function to get parent too.您也可以使用最接近的函数来获取父级。 Get closest ul to my element.
获得最接近我的元素的 ul。
var el = document.getElementById('myLi'); var el = document.getElementById('myLi');
var r1 = el.closest("ul"); var r1 = el.closest("ul");
You can use document.getElementById("myLI").parentElement.id您可以使用 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.