我已经有 3 个段落,需要使用 JavaScript 创建第 4 个段落 创建成功。
const new_h2 = document.createElement('h2')
并为 h2 分配一个 ID
new_h2.setAttribute('id', 'heading4');
现在我得到了 h2 及其 ID
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')
我猜这来自 header4.style.color
但我不知道如何处理。
听起来您从未将
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 中,以便使用
getElementById
或 querySelector
等方法在 DOM 中找到它。
但请注意,您已经拥有对该元素的引用(
new_h2
)。无需查找,也可能无需有 id
。只需使用new_h2
。 (不过,您可能仍然需要将其添加到页面中。)
旁注:您不需要使用
setAttribute
来设置元素的 id
,您可以使用 reflected 属性:
new_h2.id = "heading4";
在调用
new_h2
之前,您必须将通过 JavaScript 创建的 document.getElementById('heading4')
插入到 DOM 中:
const new_h2 = document.createElement('h2')
new_h2.setAttribute('id', 'heading4')
// Added it to the DOM
document.body.appendChild(new_h2)
// Then you can query it
const heading4 = document.getElementById('heading4')