Search code examples
javascriptdom-eventsyui

How can I reference the element that contains the event from the function called?


From inside of the fireAlert() function, how can I reference the element that called it, without having to pass this as an argument through the link?

<script type="text/javascript">

//function
function fireAlert(){
    alert();
}

</script>

<a href="javascript:;" onclick="fireAlert();">Fire</a>

Solution

  • There are easier ways of doing this with jQuery,but this is how it's done without it:

    UPDATE: Please try the following HTML/Javascript code. Notice how I am attaching the onclick event inside of window.onload instead of specifying it as an attribute at the element.

    For this example, I'm attaching the event to all anchor tags in the page, but you could replace getElementsByTagName with getElementById for a specific one.

    <html>
        <head>
            <script language="javascript">
            function fireAlert(e)
            {
                var whoCalled = e ? e.target : event.srcElement;
    
                alert(whoCalled.innerHTML);
            }
            window.onload=function()
            {
                var allHrefs = document.getElementsByTagName("a");
                for(i=0;i<allHrefs.length;i++)
                {
                    allHrefs[i].onclick=fireAlert;
                }
            }
            </script>
        </head>
        <body>
            <a href="#">Hello #1</a>
            <a href="#">Hello #2</a>
            <a href="#">Hello #3</a>
            <a href="#">Hello #4</a>        
        </body>
    </html>