How to add text in a html page using javascript ?

Active March 08, 2022    /    Viewed 60    /    Comments 0    /    Edit


Examples of how to add text in a html page using javascript:

Add text using innerHTML

<!DOCTYPE html>
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>

        <div id="intro">
                <h1>Learning Javascript</h1>
                <p>First paragraph</p>
        </div>

        <script>

            document.querySelector("#intro").innerHTML +=
                "<p>Second paragraph</p>";

        </script>

    </body>
</html>

How to add text in a html page using javascript ?

Add text using creating elements and text nodes

Another solution is

    <!DOCTYPE html>
    <html lang="en" dir="ltr">
        <head>
            <meta charset="utf-8">
            <title></title>
        </head>
        <body>

            <div id="intro">
                    <h1>Learning Javascript</h1>
                    <p>First paragraph</p>
            </div>

            <script>

                var mytag = document.createElement('p');
                var mytext = document.createTextNode('Second paragraph');

                mytag.appendChild(mytext);

                var div = document.querySelector("#intro");

                div.appendChild(mytag);

            </script>


        </body>
    </html>

How to add text in a html page using javascript ?

References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!



Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount