Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Change loaded content in an HTML file with javascript

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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>";
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading