2. Generating output

2.4. Inserting Output Inside an HTML Element


          You can display your output using an HTML element. In order to do this, you must first select the HTML element. Accessing the HTML element requires you to use the method, document.getElementById(id). The id attribute will define which HTML element is used to display your output. Inserting the output will need the .innerHTML property. Here is the code to properly use this output statement:

document.getElementById(id).innerHTML = “Your inserted output”;

This can also be written in a shorter form:

id.innerHTML = “Your inserted output”;

Take note that this method is case sensitive. Thus, make sure that the correct case for each keyword is used.

Sample Code:


          In the example given above, the “Hello World!” is displayed within the element p with id=”greet”. Basically, the .innerHTML replaces the existing content of the element. This method is used to write a dynamic html on the html document. It is usually used in registration forms, comment forms and links where you can create html form when a user clicks on a button.

          The location of the <script> is also important. If the <script> is placed before the selected element to be used, there will be no effect on the page. That is because the element that the script is trying to get has not been rendered on the browser, hence, the error would be, the object does not exist yet.