If you're looking for a simple way to create JavaScript-generated text without removing most or all the content on the web page, than this code does the job. Using document.getElementById / innerHTML, this is the improved, template-based alternative to using the document.write() function. HTML was included to show how the script works.

As you can see, the button is used to activate the function, instead of being displayed on page load. For example, if a math function was calculated, the text would be displayed on a manually-activated event to show its usability. If the code were to be placed without a function, then the text would display on the load of the page. In the script itself, simple variables were used, having the document class set the id. If the variable that was used included the existing div (in this case, "myDiv") existed, then innerHTML would let text be written inside of it.

Furthermore, variables are also accepted in the innerHTML area. For example, a variable called 'jk' is defined as a number value in document.write(jk) of the same function.

TB.innerHTML = jk

I will be working to continue to improve the script, as needed (hopefully I checked the search feature thoroughly and found nothing like this), or make variations. This code has been tested in Firefox 12.0, Explorer 8, and Opera 11.61 for the initial post; all work satisfactorily. In addition, this may also work as a separate file in the .js file extension.

EDIT: Improved version in next post.

Dormilich

05-04-2012, 07:34 AM

note, you might get into nasty nesting if you require more elements to be present. I would recomment to error out if any element access fails.

function sb()
{
var TB = document.getElementById('myDiv');
if (!TB) {
throw new Error("The element with the ID 'myDiv' does not exist.");
}
TB.innerHTML = "This is something placed into the div tag";
// more code ...
}
as well as not using inline JS (for cleaner HTML code):

Also, as other people (especially those new to coding) might come across this thread I’d strongly suggest having clean and valid HTML in your example, so that they don’t get off on the wrong foot and so it doesn’t spread bad code all across the internet. For example, use a correct doctype:

(Note that strict is the only type you’ll ever need if you create new documents)

And despite Dormilich having addressed this, and HTML not being too strict about that, if you use inline event handlers, for good practice you should write them all lowercase: onclick="…". But really, you shouldn’t have them in the HTML in the first place.

felgall

05-05-2012, 12:29 AM

(Note that strict is the only type you’ll ever need if you create new documents)

That doesn't just apply to HTML - it also applies to JavaScript.

All new JavaScript should be written to run in strict mode by placing the statement "use strict"; at the top of the JavaScript.