JavaScript: Where to Insert JavaScript and output

时间:2023-06-04 17:37:50

1、Javescript in <head>

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body> <h2>JavaScript in Head</h2> <p id="demo">A Paragraph.</p> <button type="button" onclick="myFunction()">Try it</button> </body>
</html>

2、Javescript in <body>

<!DOCTYPE html>
<html>
<body> <h2>JavaScript in Body</h2> <p id="demo">A Paragraph.</p> <button type="button" onclick="myFunction()">Try it</button> <script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script> </body>
</html>

3、Javescript in an external file、url、 folder

<!DOCTYPE html>
<html>
<body> <h2>External JavaScript</h2> <p id="demo">A Paragraph.</p> <button type="button" onclick="myFunction()">Try it</button> <p>(myFunction is stored in an external file called "myScript.js")</p> <script src="myScript.js"></script>
<script src="https://www.w3schools.com/js/myScript.js"></script>
<script src="/js/myScript.js"></script> </body>
</html>

writing into the html output / html elemnt / window alert box/ browser console