Javascript DOM How to - Add new method to DOM element








Question

We would like to know how to add new method to DOM element.

Answer


<!DOCTYPE html>
<html>
<body>
  <div id="test">test text</div>
<script type='text/javascript'>
<!--from   ww  w.j  a v a 2  s. co  m-->
    function hello() {
        console.log("hello world");
    }
    var x = document.getElementById("test");
    x["hello"] = hello;
    x.hello();

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

The code above is rendered as follows: