javascript - 未捕获的类型错误 : Cannot set property 'className' of null Error

标签 javascript html css dom

所以我的代码中有一个错误。错误信息是:

Uncaught TypeError: Cannot set property 'className' of null Error

这是代码:

HTML:

<section id="section-14">
    <div class="mediabox">
       <img src="product/Diffusers/Diffusers_1.jpg" alt="Diffusers">
       <h3>Diffusers</h3>
    </div>
</section>

Javascript:

document.getElementById('section-14').className = "content-current";

请有人指导我纠正我的错误。

最佳答案

将脚本添加到正文标记末尾之前。你的代码应该像这样 -

<html>
<head>
</head>
<body>
<section id="section-14">
    <div class="mediabox">
       <img src="product/Diffusers/Diffusers_1.jpg" alt="Diffusers">
       <h3>Diffusers</h3>
    </div>
</section>
<script>
document.getElementById("section-14").className="content-current";
</script>
</body>
</html>

希望这对您有帮助。

关于javascript - 未捕获的类型错误 : Cannot set property 'className' of null Error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34462987/

相关文章:

javascript - JQuery 和 Javascript 可以在同一个 .js 文件中使用吗?

javascript - 如何使用 CSS 一次显示和隐藏多个元素?

javascript - AJAX 未调用所需的 C# Controller 方法

html - 当 ng 服务 Angular 应用程序时,在组件 css 中配置的背景图像不考虑相对路径

javascript - Material.io - 某些 Material 设计库的组件未正确呈现

javascript - jQuery 将鼠标悬停在排除元素子元素的 li 上

html - 我如何使用 thymeleaf 和 spring Boot 遍历 ArrayList?

html - 灵活响应移动

css - 如何检查核心文件是否已更改

html - 如何使用 SVG clipPathUnits ="objectBoundingBox"