Javascript DOM How to - Override appendChild() method from Element








Question

We would like to know how to override appendChild() method from Element.

Answer


<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
div {<!--from w  w w  .  j  av  a 2  s  .  co  m-->
  height: 20px;
  background-color: red;
}
</style>

</head>
<body>
<script type='text/javascript'>

    var f = Element.prototype.appendChild;
    Element.prototype.appendChild = function(){
       f.apply(this, arguments);arguments[0].innerHTML="!Intercepted!"; 
    };
    document.body.appendChild(document.createElement("div"));

</script>
</body>
</html>

The code above is rendered as follows: