let div = document.getElementById('parentId');
// This will return a nodeList with the child div
console.log(div.childNodes);
// This will return an undefined
console.log(div.firstChild);
// This will return 0
console.log(div.childNodes.length);
<div id="parentId" class="column-">
<div class="item water" id="childId"></div>
</div>
我正在构建一个使用 MVC 结构的 javascript 应用程序。 现在我正在尝试从 div 中检索数据
当我console.log(div.childNodes)时,这个div有一个子节点
子节点出现,但是当我尝试检索子节点本身时 我总是得到一个不确定的回报 当我尝试使用长度时它返回 0
已经列出了一长串可能的方法来检索子节点,但我似乎从来没有只给我子节点未定义和0长度
我搜索了如何检索子节点、检索子节点的最佳方法等等,但没有一个解决方案可以解决我的问题
结果输出:https://pasteboard.co/IkrPqqa.jpg
我怀疑其中一个会返回第一个子节点 但它返回未定义
有人看到我做错了什么吗?
如果您尝试选择子项,请使用“.children[index]”
document.querySelector("#parentId").children[0];
节点类型有很多种(元素节点、文本节点……)。
如果您只需要检索Element节点(例如“div”),您可以执行以下操作:
let div = document.getElementById('parentId');
var lengthChildren = div.childNodes.length;
for (var i = 0; i < lengthChildren; i++) {
// Only node type "Element node"
if (div.childNodes[i].nodeType == 1)
{
console.log(div.childNodes[i]);
}
}
有关节点类型的列表,请查看此处:
https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
HTML 中的节点和元素不是一回事。虽然元素是节点,但节点并不总是元素。
方便的元素 getter 函数:
下面我重构了给定的代码以获得期望的结果。
let div = document.getElementById('parentId');
/*
// This will return a nodeList with the child div
console.log(div.childNodes);
// This will return an undefined
console.log(div.firstChild);
// This will return 0
console.log(div.childNodes.length);
*/
// This will return an HTMLCollection with the child div
console.log(div.children);
// This will return the child div element
console.log(div.firstElementChild);
// This will return 1
console.log(div.children.length);
<div id="parentId" class="column-">
<div class="item water" id="childId"></div>
</div>
一切似乎都是对的。我已经运行了你的代码,它对我有用。我在下面附上了您的代码的输出图片:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="main.css">
<script src="main.js"></script>
</head>
<body>
<div id="parentId" class="column-">
<div class="item water" id="childId">12</div>
</div>
<script>
let div = document.getElementById('parentId');
console.log(div.childNodes);
// This will return an undefined
console.log(div.firstChild);
console.log(div.firstElementChild);
console.log(div.childNodes[0]);
console.log(div.childNodes['0']);
console.log(div.childNodes["0"]);
// This will return 0
console.log(div.childNodes.length);
</script>
</body>
</html>