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
  • 1,932
  • 5
  • 14
  • 28

1 Answers1

1

function showAlert() {
          alert('Hello World')
        }
        
 document.getElementById('test').addEventListener('click', showAlert)
<div id='test' >x</div>
DCR
  • 12,959
  • 11
  • 46
  • 96
  • 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