Milad
Milad

Reputation: 67

Why can’t I have a function named "write" at global scope invoked from an event attribute?

my very simple html code, actually my javascript code is not working, here is my code:

<!DOCTYPE html>
<html>
  <head>
    <script>
      function write() {
        document.getElementById("div1").innerHTML = "hello world";
      }
    </script>
  </head>
  <body>
    <div id="div1" onclick="write()">hello</div>
  </body>
</html> 

I want to change the <div> content to “hello world”, but when i try to do it, when I click the <div> element, its content is erased and it gives me a blank page. what am i doing wrong? any help would be appreciated.

Upvotes: 2

Views: 52

Answers (1)

kasijus
kasijus

Reputation: 334

That happens because 'write' is already defined as a method from the document object. You need to change the name of the method to something else.

Upvotes: 3

Related Questions