Unhandled Promise Rejection: TypeError: null is not an object (evaluating 'editUserUI.innerHTML = interfaceHTML')

Unhandled Promise Rejection: TypeError: null is not an object (evaluating 'editUserUI.innerHTML = interfaceHTML')

我正在尝试设置 javascript 中 ID 为“admin-edit-user-content”的 div 元素的内部 html。但是控制台在磁贴中给我错误,显然我的 document.getElementById('#admin-edit-user-content'); 为空。但是,这个元素确实存在。它在我的 body 我的 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;
});

提前谢谢你, 乔纳斯

如果您使用的是 getElementById,则 ID 前不需要 #。就这样

document.getElementById('admin-edit-user-content');

如果您使用 querySelector or querySelectorAll,则使用 #

缺少一些代码,因此我无法预测太多。 检查这个:

  1. 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>