首页 > 解决方案 > JS DOM insertBefore() 无法正常工作

问题描述

我想在网站页脚之前在 JS DOM 中添加一个 div。但是,它不起作用(它将 div放在页脚之后)

const div = document.createElement('div');
div.innerHTML = "Hello!";

const footer = document.getElementById('footer');

document.body.insertBefore(div, footer);

HTML:

<footer id="#footer">This is footer</footer>

我之前添加了 .js 文件</body>

标签: javascriptdom

解决方案


页脚中的 id 有一个额外的“#”,因此 Js 选择器无法正常工作。尝试删除它:

<footer id="footer">This is footer</footer>

推荐阅读