How to Add JavaScript in HTML Document
How to Add JavaScript in HTML Document
1. Inline JavaScript
{...}
Click Here
</button>
{...}
<head>
<script>
function myFun() {
document.getElementById("demo")
</script>
</head>
{...}
<body>
<h2>
</h2>
GeeksforGeeks
</h3>
Click Here
</button>
<script>
function myFun() {
document.getElementById("demo")
</script>
</body>
function myFun () {
document.getElementById('demo')
.innerHTML = 'Content Changed'
Using innerHTML
To access an HTML element, you can use
the document.getElementById(id) method.
Then use the innerHTML property to change the HTML content of the HTML
element:
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "<h2>Hello World</h2>";
</script>
</body>
</html>
Using innerText
To access an HTML element, use the document.getElementById(id) method.
Then use the innerText property to change the inner text of the HTML element:
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerText = "Hello World";
</script>
</body>
</html>
Using document.write()
For testing purposes, it is convenient to use document.write():
Example
<!DOCTYPE html>
<html>
<body>
<script>
document.write(5 + 6);
</script>
</body>
</html>
Using window.alert()
You can use an alert box to display data:
Example
<!DOCTYPE html>
<html>
<body>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
Example
<!DOCTYPE html>
<html>
<body>
<script>
alert(5 + 6);
</script>
</body>
</html>
Using console.log()
For debugging purposes, you can call the console.log() method in the browser to
display data.
Example
<!DOCTYPE html>
<html>
<body>
<script>
console.log(5 + 6);
</script>
</body>
</html>
JavaScript Print
JavaScript does not have any print object or print methods.
The only exception is that you can call the window.print() method in the browser
to print the content of the current window.
Example
<!DOCTYPE html>
<html>
<body>
</body>
</html>
const Yes No No No No