-5

I have written this code.

  document.getElementById('show').onclick = function()

But I tried clicking "show" and instead it does not open and it indicates me as an error. So anyone have a solution ?

Zean
  • 35
  • 1
  • 6
  • Do you have a function body (in {}) that shall be executed? – STh Apr 06 '21 at 06:08
  • And could you provide us the error message? – STh Apr 06 '21 at 06:20
  • Uncaught TypeError: Cannot read property 'addEventListener' of null. – Zean Apr 06 '21 at 06:38
  • Then it seems to be that there is no element with the ID show. Watch into @marmeladze s answer for the correct declaration. – STh Apr 06 '21 at 06:42
  • Does this answer your question? [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Sebastian Simon Apr 06 '21 at 06:59

3 Answers3

-1
 document.getElementById('show'). addEventListener("click", function() {})

Would be the correct syntax but it really just depends what you want to do

SimonC
  • 59
  • 3
-1

Try function name without the brackets

document.getElementById("show").onclick = function;

See also addEventListener.

Ajmal
  • 99
  • 1
  • 6
-2

it's sample on w3schools

You can try it.

    <!DOCTYPE html>
<html>
<body>

<p>This example uses the HTML DOM to assign an "onclick" event to a p element.</p>

<p id="demo">Click me.</p>

<script>
document.getElementById("demo").onclick = myFunction();

function myFunction() {
  //your codes here Zean
  document.getElementById("demo").innerHTML = "YOU CLICKED ME!";
}
</script>

</body>
</html>
STh
  • 746
  • 9
  • 24