How to insert the data in a web page dynamically?

To insert the data in a web page dynamically use <div></div> tag or <span></span> tag

The data inserted with  <div></div> goes to new line. It is a block tag.

The data inserted using <span></span> tag remains in same line. It is inline tag.

Define an ID to these tags and get reference of that  ID using document.getElementById() function

Use innerHTML property to insert HTML contents

Use innerText properyt to insert the Text contents.


Example 1

Create a web page having a multiline text box using <textarea></textarea> tag. When we type some HTML code into the web page, show the code along with its output in same web page.

Hint: Event will be keyup

<!DOCTYPE html>
<html>
    <head>
        <script>
            function display(){
                var x=document.getElementById("x");
                var y=document.getElementById("y");
                var t=document.getElementById("t");
                x.innerText=t.value;
                y.innerHTML=t.value;
            }
        </script>
    <head>
    <body>
        <textarea id="t" rows="10" cols="50" onkeyup="display()"></textarea>
        <div id="x"></div>
        <div id="y"></div>
    </body>
</html>

Example 2

Create a web  page having a text box to input a number.
Show the factorial of that number when a number is typed in front of the text box.
The output format will be like
The factorial of <num> is <factorial>

<!DOCTYPE html>

<html>
    <head>
        <script>
            function showresult(){
                var n=parseInt(document.getElementById("num").value);
                var f=1;
                for(i=1;i<=n;i++)
                    f=f*i;
                var ot="The factorial of <span style='font-weight:bold;color:blue'>" + n + "</span> is <span style='font-weight:bold;color:red'>" + f + "</span>";
                document.getElementById("output").innerHTML=ot;
            }
        </script>
    <head>
    <body>
        <input type="number" id="num" onkeyup="showresult()"> <span id="output"></span>
    </body>
</html>

Comments