![]() |
document.getElementById() / innerHTML; An alternative snippet to document.write()
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.
Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">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. Code:
TB.innerHTML = jkEDIT: Improved version in next post. |
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.
PHP Code:
PHP 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:
Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">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. |
Quote:
All new JavaScript should be written to run in strict mode by placing the statement "use strict"; at the top of the JavaScript. |
Improved version (previous version still acceptable):
Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> |
| All times are GMT +1. The time now is 08:28 AM. |
Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.