Home > database >  Why does this JavaScript work in <script> tag but not with src
Why does this JavaScript work in <script> tag but not with src

Time:02-03

JS:

window.onload = function siteTitle() {
const element = document.getElementById("site-title");
element.innerHTML = "New Heading";
};

HTML:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Title</title>
        <link rel="stylesheet" href="styles.css" />
    </head>
    <body onl oad="siteTitle()">
        <h1 id="site-title" >Site Title</h1>
        <div >
        <div >
            a
        </div>
        <div >
            <h1 >abc</h1>
            a
        </div>
        </div>
        
        <script src="main.js"></script>
        
    </body>
</html>

I have tried changing it multiple times with things I have found from other questions and website but I cannot fix this The script worked when placed directly in the tag but not when imported Thank you for your help

CodePudding user response:

The following codes works for me well. If these codes doesn't work for you, check your browser and update it.

try

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Title</title>
    <link rel="stylesheet" href="styles.css" />
    <script src="main.js"></script>
  </head>
  <body>
    <h1 id="site-title" >Site Title</h1>
    <div >
      <div >a</div>
      <div >
        <h1 >abc</h1>
        a
      </div>
    </div>
  </body>
</html>

with

window.onload = () => {
  const element = document.getElementById("site-title");
  element.innerHTML = "New Heading";
};

CodePudding user response:

Since you're calling the function from <body onl oad="siteTitle()"> you need to define it with a normal function definition, not by assigning to window.onload.

function siteTitle () {
    const element = document.getElementById("site-title");
    element.innerHTML = "New Heading";
};

CodePudding user response:

Try giving a name to your function like this

window.onload = function siteTitle() {
const element = document.getElementById("site-title");
element.innerHTML = "New Heading";
};

because you are giving siteTitle as a function but it is a parameter I am not sure but it can work for you.

  • Related