'JavaScript Onclick Function Fails to Execute [closed]

I have a button that triggers an onclick function:

<!DOCTYPE html>

<body>
    <h2>what can javascript do?</h2>

    <p Id="demo"></p>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script>
       <button type="button" onclick='document.getElementById("demo").innerHTML = "Hello Javascript!"'>Click Me!</button>
    </script>
</body>
</html>

when clicking the button, I found that the onclick does not trigger. What might be the problem with my code?



Solution 1:[1]

  • You don't need jQuery
  • Use addEventListener instead and set an ID to your button Element
  • use textContent (instead of innerHTML)
  • Add the missing <html> tags etc
  • Use type="button" on a Button Element (since by default is of type "submit")

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Demo</title>
</head>

<body>
  <h2>what can javascript do?</h2>

  <button type="button" id="demoButton">Click Me!</button>

  <p id="demo"></p>


  <script>
    const elDemo = document.querySelector("#demo");
    const elButton = document.querySelector("#demoButton");

    elButton.addEventListener("click", () => {
      elDemo.textContent = "Hello Javascript!"
    });
  </script>
</body>

</html>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Roko C. Buljan