3

Some content, in this case a navbar (navbar.php), is loaded into the index.html by Javascript. Now I want to change a navbar list item from "Home" to "Something else" using Javascript. But it seems that the script can not see the loaded content. The console gives an „document.getElementById(...) is null“ error. Following the code:

index.html

<!DOCTYPE html>
<html lang="de">
  <head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
      $(function() {
        $("#navbar").load("navbar.php");
        return false;
      });
    </script>
  </head>
  <body>
    <div class="container">
      <div class="row">
        <header>
          <div id="navbar">

          </div>                        
        </header>
        <main>
        
        </main>
        <footer>
        
        </footer>
        <script>
          let myChange = document.getElementById("change").innerHTML;                   
          myChange = "<a href='somethingelse.html'>Something else</a>";
        </script>
      </body>
    </div>
  </div>
</html>

navbar.php

<div>
  <ul>
    <li id="change"><a href="index.html">Home</a></li>
    <li ><a href="logout.php">Logout</a></li>
  </ul>
</div>

Any idea what is wrong in the code? Thanks a lot in advance.

2
  • innerHTML is not a reference to it. You are storing the string into the variable. let myChange = document.getElementById("change");myChange.innerHTML='foo'; Commented Jun 2, 2022 at 21:20
  • 2
    You are reading the element before it exists. You would have the code run after the load runs. Commented Jun 2, 2022 at 21:21

1 Answer 1

3

You would need to use the load's callback function for load to know when the content has been added to the document.

$("#navbar").load("navbar.php", function() {
  const myChange = document.getElementById("change");
  myChange.innerHTML = "<a href='somethingelse.html'>Something else</a>";
});
Sign up to request clarification or add additional context in comments.

1 Comment

many thanks, that was the trick.... thumbs up

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.