【发布时间】:2022-12-18 04:23:43
【问题描述】:
我制作了一个跨度数组,当我控制台记录它时,我可以看到它包含我想要的所有元数据(也许元数据在这里是错误的词)。
但是,当我遍历代码和 console.log 时,所有元数据的每个项目都消失了,它只显示内部文本。
这是一个问题,因为我试图访问父元素,但它返回 null。
我试过使用 console.dir 而不是 console.log 但结果完全空白。
我的 JavaScript 在下面,感谢您的任何输入!
// Select all <span> elements
const spanElements = document.querySelectorAll('span');
// Convert the NodeList to an array
const spanArray = Array.from(spanElements);
// Select all <span> elements containing the estimated job length
const lengthElements = spanArray.filter(element => element.innerText.includes('Estimated job length:'));
console.log('lengthElements ', lengthElements)
// Create an array to store the estimated job lengths
const lengths = [];
// Loop through the selected elements and extract the estimated job lengths
for (let i = 0; i < lengthElements.length; i++) {
console.log(`lengthElements[${i}] `, lengthElements[i])
// Get the text inside the <span> element
const text = lengthElements[i].innerText;
console.log(`text ${text}`)
// Extract the hours and minutes from the text
const [hours, minutes] = [text.split(' ')[3], text.split(' ')[5]]
// Get the checkbox element with the corresponding id
const checkbox = document.getElementById(lengthElements[i].parentElement);
console.log('length checkbox', checkbox)
// Check if the checkbox is checked
if (checkbox.checked) {
// Add the hours and minutes to the array if the checkbox is checked
lengths.push({ hours: Number(hours), minutes: Number(minutes) });
};
}
【问题讨论】:
-
请张贴您尝试的minimal reproducible example,注意输入和预期输出,最好是Stacksnippet
-
控制台列出了 DOM 节点的所有可能属性,并指出在您的情况下它们是
null。您正在使用的节点实际上并不包含这些属性(因此是null),因此没有任何内容“丢失”。 -
我很确定你遇到的问题在这里:
document.getElementById(lengthElements[i].parentElement)。 getElementById 希望您传递一个 ID,但您传递的是一个 DOM 节点。
标签: javascript html