未处理的承诺拒绝:TypeError:null 不是对象(评估“editUserUI.innerHTML = interfaceHTML”)
2021-05-12
2466
我试图在 javascript 中设置 id 为“admin-edit-user-content”的 div 元素的内部 html。但控制台在图块中给出了错误,显然我的
document.getElementById('#admin-edit-user-content');
为空。但是,这个元素确实存在。它在我的 index.html 主体中:
<html lang="nl">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
</head>
<body class="grey lighten-3">
<!-- There's a lot of other code here that is not relevant right now -->
<div id="modal-admin-edit-user" class="modal">
<div class="modal-content">
<h4>Gebruiker bewerken</h4>
<div id="admin-edit-user-content">
<!-- inner html goes here -->
</div>
</div>
</div>
<!-- Some more code -->
<script src="/scripts/index.js"></scripts>
</body>
</html>
然后在我的 index.js 中:
// A lot of code goes before this
// this function is called on a button press
function updateEditUserUI(uid) {
// editUserUI is null and I don't understand why
const editUserUI = document.getElementById("#admin-edit-user-content");
const interfaceHTML = `
<p>Some inner html, I've gotten rid of all the details because they are not relevant for this question</p>
`;
// Right here I get the exception:
editUserUI.innerHTML = interfaceHTML;
}
// more code
有人知道为什么会发生这种情况吗?因为我完全没有主意了。
我尝试仅在以下示例中的 cont 变量为真时执行代码,但这没有帮助。
var cont = false;
document.addEventListener('DOMContentLoaded',() => {
cont = true;
});
提前谢谢您, Jonas
2个回答
如果您使用的是
getElementById
,则不需要在 ID 前添加
#
。只需执行
document.getElementById('admin-edit-user-content');
如果您使用
querySelector
或
querySelectorAll
,则使用
#
。
bub
2021-05-12
缺少一些代码,因此我无法预测。 检查一下:
- document.getElementById("#admin-edit-user-content"); //不需要 #
希望这有帮助:
<html lang="nl">
<body class="grey lighten-3">
<!-- There's a lot of other code here that is not relevant right now -->
<div id="modal-admin-edit-user" class="modal">
<div class="modal-content">
<h4>Gebruiker bewerken</h4>
<div id="admin-edit-user-content">
<!-- inner html goes here -->
</div>
</div>
</div>
<button onclick="updateEditUserUI()">Your Button</button>
<!-- Some more code -->
<script>
function updateEditUserUI() {
// editUserUI is null and I don't understand why
const editUserUI = document.getElementById("admin-edit-user-content");
const interfaceHTML = "<p>Some inner html</p>";
// Right here I get the exception:
editUserUI.innerHTML = interfaceHTML;
};
</script>
</body>
</html>
Mayukh Roy
2021-05-12