Home > database >  Change loaded content in an HTML file with javascript
Change loaded content in an HTML file with javascript

Time:06-03

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

CodePudding user response:

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

CodePudding user response:

Since you are using jQuery you might as well use it consistently:

<html lang="de">
  <head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
 const navbar_php=`<div>
  <ul>
<li id="change"><a href="index.html">Home</a></li>
<li ><a href="logout.php">Logout</a></li>
  </ul>
</div>`;
 $(function() {
  $("#navbar").html(navbar_php); // emulating  .load("navbar.php")
  $("#change").html("<a href='somethingelse.html'>Something else</a>");
  return false;
 });
</script>
  </head>
  <body>
<div >
  <div >
    <header>header
      <div id="navbar">
      </div>                        
    </header>
    <main>main content 
    </main>
    <footer>footer
    </footer>
  </body>
</div>
  </div>
</html>

You could use load()'s.callnack function, as epascarello suggests, but you can just as well place the $("#change").html(...) expression after the .load() expression.

  • Related