Home > Mobile >  getElementById does not call the HTML ID
getElementById does not call the HTML ID

Time:08-16

I have a folder with two files each, once the HTML file, and once the JS file to make everything clearer. My problem now is that I try to access an ID within the HTML file with the getElementById but this doesn't seem to work.

var score = 0;

score = score   1;
document.getElementById("score").outerHTML = score;
<!DOCTYPE html>
    <head>
        <title>Clicker Game</title>
        <link rel="stylesheet" href="design.css">
        <script src="code.js" type="text/javascript"></script>
    </head>

    <body>
        <p>Cookies: <span id="score">0</span></p>
        <img src="images/cookie.png" height="256px" width="256px">
    </body>
</html>

I am trying to call the ID "score" in the HTML file to make sure that when I start the HTML file locally the number changes from 0 to 1.

CodePudding user response:

Click on the number in the HTML file, which will change the value. You cannot change the value without a trigger in the HTML. Something needs to be clicked or changed for the value to appear. Edit: And don't grab the outerHTML of the element. You are erasing the whole score span and replacing it with the count. Use textContent instead.

let elem = document.querySelector("#score");

elem.addEventListener("click", (e) => {
  elem.textContent = Number(elem.textContent)   1;
})
#score {
  cursor: pointer;
}
<!DOCTYPE html>

<head>
  <title>Clicker Game</title>
  <link rel="stylesheet" href="design.css">
  <script src="code.js" type="text/javascript" defer></script>
</head>

<body>
  <p>Cookies: <span id="score">0</span></p>
  <img src="images/cookie.png" height="256px" width="256px">
</body>

</html>

CodePudding user response:

JavaScript cannot get the elements in HTML before the HTML rendering is completed. The operation of importing JS files should be placed after the rendering, that is, after

  • Related