0

I am trying to make a function where I can just put showAlert() after an element name and it will show an alert when clicked. I have defined my showAlert function in my JavaScript, but I always get an error.
I've tried:

        function showAlert() {
             return onclick = "alert('Hello World')"
        }

            document.getElementById('test').showAlert();

The code above should return: "document.getElementById('test').onclick = "alert('Hello World')",
However, I get an error saying: document.getElementById(...).showAlert is not a function

Thanks for any help.

Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35

1 Answers1

1

function showAlert() {
          alert('Hello World')
        }
        
 document.getElementById('test').addEventListener('click', showAlert)
<div id='test' >x</div>
DCR
  • 14,737
  • 12
  • 52
  • 115
  • I know that this is a way to do it but I want it to be a function that can just be placed after any element name, like: document.getElementById('test').showAlert() instead of adding the onclick event to the element. – user9719238713 Jan 14 '21 at 19:21
  • snippet updated – DCR Jan 14 '21 at 19:33