LanguagesJavaScriptUsing JavaScript to Create HTML Tags

Using JavaScript to Create HTML Tags content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Tips! My Man…

At the same time I’m writing this Script Tip, I’m also editing a JavaScript book. Just so I can keep a timeline straight in my own mind, we’ll use the script I’m currently working on in the book as our new script here.

Click here to see the script in action

The script will ask the viewer what background and text colors they would like, then the page will display with those colors. Finally, the viewer will be told, in the status bar, “Here’s your color background and color text.”

Up until now, the JavaScripts we’ve used could basically sit where you wanted the document.write statement to print to the page. With this script, we’re actually concerned with where it will sit in the HTML document.

The quickest way to implement the user’s background and text color requests would be to write them to the <BODY> tag.

This script’s main purpose is to write the HTML document’s <BODY> tag to the page so we have to make sure that the entire script sits right where the <BODY> sits on the HTML page. And of course, we need to make sure we don’t write a <BODY> tag into the HTML document ourselves. We need to let the script do that for us.

Here’s the code that writes the <BODY> tag.

document.write("<BODY BGCOLOR=" +color+ " TEXT=" +txtcolor+ ">") 

You already know what the double quotes and plus signs mean. The double quotes surround text to be written to the page, while the plus signs surround something that will be returned from the script somehow. In this script we know that data will come from the user because we’re using two prompt commands to ask for colors.

Let’s set up an example. If the user enters “blue” as the page background and “yellow” as the text color, this will be written to the page as the <BODY> tag:

<BODY BGCOLOR="blue" TEXT="yellow">

And since we have placed the script so that that line is written where the <BODY> tag would normally go, it acts as the <BODY> tag for the page. Thus the command runs and we see the color combinations on the page. Very clever.

Next Time: How Did That Text Get Into The Status Bar?

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories