Javascript DOM How to - Add method to window and HTMLElement








Question

We would like to know how to add method to window and HTMLElement.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
window.onload=function(){<!--from w  w w . j  a va  2 s.  c om-->
window.something = function(){ 
    console.log('global');
}
HTMLElement.prototype.something = function(){
    console.log('element');
}
}
</script>
</head>
<body>
  <a onclick="something();">Click Me</a>
  <br>
  <a onclick="this.something();">And Me</a>
  <br>
  <a onclick="window.something();">Now Me</a>
</body>
</html>

The code above is rendered as follows: