How to Write HTML Elements in Javascript


Javascript


In this article, we will go over how HTML elements, such as a p tag (paragraph tag) or a br tag (break tag), etc., can be written within a script of Javascript.

Many times javascript text alone will not be sufficient for a web page. We may need to add different elements such as a break in the text or put the whole text within a paragraph. How can we insert these HTML elements into javascript code so that have these elements visible on a web page?

To do this in javascript, we use the document.write() function, using the following format:

The HTML elements that is desired to be displayed is placed within single quotes within the parentheses of the document.write() function.

Example of HTML Elements in Javascript Code

The above code places the opening paragraph tag within a script of javascript.

To place a closing paragraph tag within the script, we would put:

Therefore, if we wanted to place a opening and closing paragraphs tags within a script of Javascript, we would use the lines:

Or, as a shortcut, we could rewrite this so that it just takes up one line of code, shown below:

Actual Javascript Output of Above Code




If we want to place a header into Javascript code, we place the following lines in the code:

Actual Javascript Output of Above Code




If you want to insert another kind of HTML element into Javascript code such as an img tag (for an image), the following lines of code would be:

Actual Javascript Output



If you want to insert an img tag with an alt tag and width and height size dimensions, we use double quotes for the values of the width, height, and alt attributes. However, no semicolons should appear anywhere in the img tag. If it does, the code will not work. Javascript will see the semicolon (;) as where the code ends. All semicolons must be removed from the img tag.

The code will look as such below:



Thus, if we want a reduced size of the above bmw hybrid photo, we can do so with the above code.

Actual Javascript Output



We can place any HTML element in Javascript code using the document.write('') function with single quotes in between the parentheses. Anything we can do in regular HTML, we can do in Javascript code. This can lead to very dynamic Javascript code which can create dynamic websites.

HTML Comment Box is loading comments...