Programming Examples

Are you a Programmer or Application Developer or a DBA? Take a cup of coffee, sit back and spend few minutes here :)

JavaScript 003 – Document Object

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:

Javascript Write String to document
Javascript Write String to document

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:

Javascript Write String to document - output
Javascript Write String to document – output

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

Categories: JavaScript

Tags: , ,

Do you like this Example? Please comment about it for others!!

This site uses Akismet to reduce spam. Learn how your comment data is processed.