Wednesday, August 20, 2014

onclick event handler - get reference to the clicked element

There are a couple of ways to get the reference to the clicked element, which has onclick event on itself.


Method 1
<input type="button" id="btn1" value="Remove" onclick="removeSelf(event)" />

<script type="text/javascript">
  function removeSelf(e){
    var target = (e.target) ? e.target : e.srcElement // IE uses srcElement
    target.style.display = 'none'; 
    target.parentNode.removeChild( target ); // to remove the element
    $(target).remove(); // to remove the element using jQuery
  }
</script>

In Method 1, event is used as parameter. An Event object is created automatically whenever an event is fired, i.e., via user action, key press, mouse movement, etc. To find the source where the event occurred, the property name is either target or srcElement (in IE).


Method 2
<input type="button" id="btn1" value="Remove" onclick="removeSelf(this)" />

<script type="text/javascript">
  function removeSelf(object){    
    object.style.display = 'none';
    target.parentNode.removeChild( target ); // to remove the element
    $(target).remove(); // to remove the element using jQuery
  }
</script>


No comments: