首页javascriptelementJavascript DOM - 如何为DOM元素添加新方法

Javascript DOM - 如何为DOM元素添加新方法

我们想知道如何为DOM元素添加新方法。

<!DOCTYPE html>
<html>
<body>
  <div id="test">test text</div>
<script type='text/javascript'>

    function hello() {
        console.log("hello world");
    }
    var x = document.getElementById("test");
    x["hello"] = hello;
    x.hello();

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