【问题标题】:setAttribute for created element已创建元素的 setAttribute
【发布时间】:2021-12-31 08:11:23
【问题描述】:

我已经有 3 段,需要使用 JavaScript 创建第 4 段 已成功创建。

const new_h2 = document.createElement('h2')

并为 h2 分配一个 ID

new_h2.setAttribute('id', 'heading4');

现在我得到了带有 ID 的 h2

const heading4 = document.getElementById('heading4')

当我尝试在 If 语句中使用它时出现问题

    window.addEventListener('scroll', function(){
        console.log(window.scrollY);
        if(window.scrollY >= 400 && window.scrollY < 800){
            heading1.style.color = '#cc1'
            // console.log('section1 is styled');
        }else if(window.scrollY >= 800 && window.scrollY < 1200){
            heading2.style.color = '#cc1'
            // console.log('section2 is styled');
        }else if(window.scrollY >= 1200 && window.scrollY < 1600){
            heading3.style.color = '#cc1'
            // console.log('section3 is styled');
        }else if(window.scrollY >= 1600){
            heading4.style.color = '#cc1'
            // console.log('section4 is styled');
        }else{
            heading1.style.color = '#fff'
            heading2.style.color = '#fff'
            heading3.style.color = '#fff'
            heading4.style.color = '#fff'
        }
})

日志显示以下错误: Cannot read properties of null (reading 'style') 我猜这来自heading4.style.color 但我不知道如何处理。

【问题讨论】:

  • 创建元素不会自动将其放入文档中。为什么不简单地使用new_h2?您已经拥有该元素。

标签: javascript createelement setattribute


【解决方案1】:

听起来您从未在页面中添加new_h2。因为它不在页面的 DOM 中,所以 getElementById("heading4") 返回 null - DOM 中没有带有 id 的元素:

const new_h2 = document.createElement("h2");

new_h2.setAttribute("id", "heading4");

console.log(document.getElementById("heading4")); // null

// Add the element to the page's DOM
document.body.appendChild(new_h2);

console.log(document.getElementById("heading4")); // finds it

您需要将元素添加到 DOM 以便使用 getElementByIdquerySelector 等方法在 DOM 中找到它。

但请注意,您已经引用了该元素 (new_h2)。无需查找它,也可能不需要id。只需使用new_h2。 (您可能仍然需要将其添加到页面中。)


旁注:您不需要使用setAttribute 来设置元素的id,您可以使用reflected 属性

new_h2.id = "heading4";

大多数(但不是全部)有用的属性都有反映的属性。您可以查看on MDNin the spec 中的哪些。

【讨论】:

  • 我认为 new_div.appendChild(h2) 应该将其添加到 DOM 中
  • @HanyTaha - 确实如此。这不是你的问题。