Search code examples
javascripthtmlnullinnerhtmlgetelementbyid

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


I am trying to set the inner html of a div element with the id "admin-edit-user-content" in javascript. But the console gives me the error in the tile, apparently my document.getElementById('#admin-edit-user-content'); is null. However, this element does definitely exist. It is in my body of my 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>

Then in my 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

Does anyone know why this happens? Because I'm completely out of ideas.

I've tried only executing the code when the cont variable in the example below was true, but this didn't help.

var cont = false;
document.addEventListener('DOMContentLoaded',() => {
    cont = true;
});

Thank you in advance, Jonas


Solution

  • If you are using getElementById, you do not need a # before the ID. Just do

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

    You use a # if you are using querySelector or querySelectorAll.