【问题标题】:looping through an array of spans seems to remove all of the metadata遍历一系列跨度似乎删除了所有元数据
【发布时间】: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


【解决方案1】:

这是一个 X/Y 问题。

共享 HTML,我可以轻松修复它。

以下不是有效的陈述,因为您没有传递 ID

document.getElementById(lengthElements[i].parentElement);

但修复它无济于事,因为您不能将复选框父元素添加到 span 或任何其他元素,因为 inputvoid element 并且在 HTML 中没有关闭标记

您需要在标签或其他容器中找到包装或包装输入和跨度。然后我将遍历最近的公共静态容器中所有选中的复选框,看看 inputElement.nextElementSiblinginputElement.closest("label").querySelector("span") 是否有文本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-13
    • 1970-01-01
    • 1970-01-01
    • 2012-11-09
    • 1970-01-01
    • 2013-06-23
    • 2014-04-19
    相关资源
    最近更新 更多