我有以下代码:
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8"/>
<script type = "text/javascript" src = "js/jquery.js" ></script>
</head>
<body>
<div id = 'div'>
<div id = "1">
</div>
<div id = "2">
</div>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我的JavaScript代码是:
$(document).ready(function(){
var lastcommentq = document.getElementById('div').lastChild.id;
alert(lastcommentq);
});
Run Code Online (Sandbox Code Playgroud)
它应警告div的lastchild的id,id为'div',即'2',但我收到警告为"undefined".我不知道我做错了什么.请帮我.
您的元素可能在它们周围有文本节点,因此外部的最后一个子节点<div>不一定具有"id"属性.
我不确定是否所有浏览器都支持它,但是有一个"lastElementChild"属性只显示元素,而不是注释节点或文本节点.如果做不到这一点,你可以遍历节点列表寻找类型1节点.