Over here, we are going to teach you 3 methods to write a message in JavaScript.
innerHTML
innerHTML
has to be tagged along with the element that you want to change using a query selector.
ℹ️ In this section, the query selector that you will learn is
getElementById()
If i were to modify the message in <p>
with id='change'
to "Hello World", I can choose the element by using getElementById("change")
and assign it with the value I want.
<!DOCTYPE html>
<html>
<head>
<title>InnerHTML</title>
</head>
<body>
<p>This is line 1</p>
<p id='change'>This is line 2</p>
<script>
document.getElementById('change').innerHTML = 'Hello World';
</script>
</body>
</html>
We need to include <script> </script>
in the <body>
of the HTML element.
You can add JavaScript code in an HTML document by employing the dedicated HTML tag <script> that wraps around JavaScript code. The <script> tag can be placed in the section of your HTML, in the section, or after the close tag, depending on when you want the JavaScript to load.
<!DOCTYPE html>
<html>
<head>
<title>This is the HTML Page</title>
</head>
<body>
<p>Let's try writing JavaScript in HTML!</p>
<p id='this'>Try This!</p>
<script>
alert('Hello World');
document.write('I love WebLaunch');
document.getElementById('this').innerHTML='Change to This!';
</script>
</body>
</html>
These are the outputs: