Skip to content

Latest commit

 

History

History
142 lines (95 loc) · 4.32 KB

how-to-write-javascript-in-html.md

File metadata and controls

142 lines (95 loc) · 4.32 KB

🚩How to write JavaScript in HTML

✔️ How to write a message in JavaScript

Over here, we are going to teach you 3 methods to write a message in JavaScript.

alert()
    alert('Hello World');

This will be the output in your browser




document.write()
    document.write("Hello World");

This will be the output in your browser




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>

Before adding <script>



After adding <script>

|


✔️ To write JavaScript in a HTML file

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:

alert('Hello World');



document.write('I love WebLaunch');



document.getElementById('this').innerHTML='Change to This!';







◀️ Previous Page : JavaScript 🚩                                               🏡                                               ▶️ Next Page : Basics of JavaScript : Variables 🔓