Javascript Element How to - Get script element in DOM tree








Question

We would like to know how to get script element in DOM tree.

Answer


<!DOCTYPE html>
<html>
<head>
</head><!--  w w  w.j  a v a  2 s .  c  o m-->
<body>
<body>
  <div id="mydiv">
    <script>
        var cs = document.currentScript;
        function clicked(){
            console.log(cs);
            console.log(cs.parentNode.id);
        }
        </script>
  </div>
  <button onclick="clicked()">click</button>
</body>
</body>
</html>

The code above is rendered as follows: