1. JavaScript ‘document’ Object
One can retrieve the loaded html document in JavaScript using its document object. Here, in this example, we will form a String and show that in the document using the JavaScript document object. Note, we can learn more about document object in future examples.
2. String in JavaScript
In JavaScript, the chain of characters represents a String. Like other programming languages, one or more strings can be attached using the + operator. This process is called String Join.
3. JavaScript Document Object Example
The example is below:

Explanation
1) Here, we declared a variable called GreetStr
and at the same assigned a string value to it. The string contains a space in the tail end as we want to append some dynamic content to it.
2) The function prompt
asks the user to enter his name. The PersonName
variable holds the data entered by the user. This string is a dynamic content as the user is entering it in the input box.
3) Here, we perform String concatenation of two variables GreetStr
and PersonName
using the + operator. After joining the string, the result is stored back in the GreetStr
variable. Note the order of the join. The left side of the + is GreetStr
.
4) Now, we have result string in the GreetStr
. Here, we use the
document object, which represents the html document getting rendered in the browser. The
writeln method will write the string content directly into the document content. We passed the greeting string as an argument to this method. One can see two more string-join done on the fly. We enclose the greeting string between the <h1>
tags via string join and + operator.
4. Running the Example
Running the above example in the browser produces the following result:
First, the browser will produce the input box to collect the username. Here, the user entered ‘Coding Example’ as the name (Marked as 1). We know that our script will join this name with a static string and prints that in the Html Document via the JavaScript’s document object. The bottom of the screen shows how the browser renders the text string in bold font (Marked as 2). This is because the Greeting String lies in between the H1 tags.
5. Code Reference
003_UseDocumentObject.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<!DOCTYPE html> <html lang="en"> <head> <title>Javascript Document</title> </head> <body> <script> //Sample 01: Initial String var GreetStr = "Wencome to JavaScript "; //Sample 02: Get String From User var PersonName = prompt("What is your Name?"); //Sample 03: Append String GreetStr = GreetStr + PersonName; //Sample 04: Write String to Html Document document.writeln("<h1>" + GreetStr + "</h1>"); </script> </body> </html> |
Categories: JavaScript