...

View Full Version : Alternative to 'document.write()' ??



Asher01
08-27-2011, 10:41 AM
I am very new to JavaScript, however I already seem semi-stumped.

The tutorial I am using, mentions that for tutorial example purposes they use document.write() however it suggests that I avoid using this as it will overwrite the whole HTML page.

I know that I can use document.getElementById() for some things... however this begs my question:

When do you use document.write(), when do you use document.getElementById() and is there also another method you use to change/write to the HTML Document using JavaScript?

Otherwise, do you just use document.getElementById() quite a lot in JavaScript?
Like I said, I'm very new to JavaScript, so it's all still very new to me.

Cheers,
Asher

Philip M
08-27-2011, 11:52 AM
document.write statements must be run before the page finishes loading. Any document.write statement that runs after the page finishes loading will create a new page and overwrite all of the content of the current page. So document.write is at best really only useful to write the original content of your page. It cannot be used to update the content of your page after that page has loaded. Also, document.write only works with pages that the browser processes as HTML. Pages the browser processes as XML cannot use document.write at all.

As you say, document.write() is mostly of use for tutorial purposes. document.write() is also used for adding script tags that load before the page finishes, commenting out some contents under certain conditions, injecting off-site remote data into a specific place in the document without server proxies, or for creating popups with dynamic content.



The proper DOM method to write to an HTML page is using document.getElementById(). Example:-



<div id = "myDiv"></div>
<span id = "mySpan"></span>
<br>
<input type = "text" id = "myTextBox" readonly>

<script type = "text/javascript">
var message = "My message";
document.getElementById("myDiv").innerHTML = message; // use innerHTML for block and inline HTML elements
document.getElementById("mySpan").innerHTML = message;
document.getElementById("myTextBox").value = message; // use the value property for input elements
</script>




"By three methods we may learn wisdom: First, by reflection, which is noblest; Second, by imitation, which is easiest; and third by experience, which is the bitterest." - Confucious

webdev1958
08-27-2011, 12:04 PM
when do you use document.getElementById() and is there also another method you use to change/write to the HTML Document using JavaScript?


You can use getElementById() whenever you want to refer to an element's object.

Say you have a <div> with an id = 'myDiv' and you want to add a <p> as a child to the <div>. You could do this:



var divObj = document.getElementById('myDiv');

var newP = document.createElement('p');
var str = 'some text...blah...blah';
newP.appendChild(document.createTextNode(str));
divObj.appendChild(newP);
Try to avoid using innerHTML to create html elements. innerHTML is not a part of the W3C DOM specifications.

Philip M
08-27-2011, 12:24 PM
Try to avoid using innerHTML to create html elements. innerHTML is not a part of the W3C DOM specifications.

No, but in fact it is supported by all major browsers. :)
See http://javascript.about.com/library/bldom06.htm

The OP says "I am very new to Javascript". There is no point in offering advanced level solutions to beginners.

webdev1958
08-27-2011, 12:38 PM
yes even though innerHTML is not in the DOM specifications, it is supported by major browsers but it's not advisable to try to create elements with it.

DOM methods including createElement(), appendChild() etc should be used to create and manipulate elements. I was taught about DOM methods in the first semester so they are hardly advanced topics.

Philip M
08-27-2011, 12:40 PM
yes even though innerHTML is not in the DOM specifications, it is supported by major browsers but it's not advisable to try to create elements with it.

DOM methods including createElement(), appendChild() etc should be used to create and manipulate elements. I was taught about DOM methods in the first semester so they are hardly advanced topics.

Yes, I agree that DOM methods including createElement(), appendChild() etc. should be used to create elements. But here were are talking about inserting a value into an existing element.

webdev1958
08-27-2011, 01:17 PM
But here were are talking about inserting a value into an existing element.

I suppose you mean the "were" is actually just you :D

I was appending a text node and you can talk about whatever you like.


There is no point in offering advanced level solutions to beginners.

Are you saying it's your decision as to what is and is not useful to the op? because I don't believe it is ;)

I'm sure the op can decide for himself what is useful or not to him :)

Go and read the op's first post and you will see


and is there also another method you use to change/write to the HTML Document using JavaScript?where nothing specific is mentioned in change/write to the HTML Document using JavaScript.

Also, I don't see a moderator's badge under your username so that means what you think of what I posted matters zero to me :)

Since you are unable to post anything showing anything I demonstrated or said is not accurate or relevant, why not just mind your own business since you are not a moderator.

webdev1958
08-27-2011, 01:56 PM
As I said, I was taught DOM methods in the first semester and so they are not advanced topics and it is up to the op to decide what is useful to them and not you.

The info I provided is inline with what the op asked since (s)he was not specific in


and is there also another method you use to change/write to the HTML Document using JavaScript? :)

DaveyErwin
08-27-2011, 02:16 PM
I know that I can use document.getElementById() for some things... however this begs my question:

When do you use document.write(), when do you use document.getElementById() Cheers,
Asher

Document write is almost a necessity when you wish to
use an alternative style sheet based on user prefference
that has been stored in a cookie some thing like this ....

<head><script>
if(document.cookie.indexOf('style=1')>=0)

document.write('<link rel="stylesheet"

type="text/css" href="../includes/style1.css">\n');
else if (document.cookie.indexOf('style=2')>=0)

document.write('<link rel="stylesheet"

type="text/css" href="../includes/style2.css">\n');
else document.write('<link rel="stylesheet"
type="text/css" href="../includes/style0.css">\n');

for another use of document write study the source code
of this page , at the bottom of source you will notice
the google analytics section.

VIPStephan
08-27-2011, 02:44 PM
Document write is almost a necessity when you wish to use an alternative style sheet based on user prefference
that has been stored in a cookie some thing like this ....

Can’t you just create and append a link element and add the appropriate attributes the standard DOM way as well? After all, as said, in XML document.write can’t be used at all.

For my personal perception the DOM way of creating and appending elements is cleaner than the innerHTML way. Maybe we can agree on this and stop the fight?
Or just agree to disagree as long as the aspirant JS developer is well informed about all possibilities, their advantages and drawbacks, so they can make their own decision what works best for them.

venegal
08-27-2011, 03:58 PM
When do you use document.write(), when do you use document.getElementById() and is there also another method you use to change/write to the HTML Document using JavaScript?

Otherwise, do you just use document.getElementById() quite a lot in JavaScript?


As has already been mentioned, document.write isn't used much outside of a simple tutorial context. Even DaveyErwin's examples, which are as real-life as it will get for document.write, are typically done differently (the cookie thing usually on the server side, since there's no user interaction anyway, and Google Analytics asynchronously by DOM manipulation).

As for the document.write vs. document.getElementById — that's an awkward comparison, because they do very different things. Let's better call it document.write vs. DOM manipulation, and the answer is: DOM manipulation all the way.

You already noticed that that would mean using a lot of document.getElementById and similar functions, which is a bit awkward too, so lots of people just drop in some framework (like jQuery), which makes all sorts of DOM manipulation very easy.



Try to avoid using innerHTML to create html elements. innerHTML is not a part of the W3C DOM specifications.

This is not true — innerHTML is part of both the W3C HTML5 specs and the WHATWG HTML Living Standard, see http://www.w3.org/TR/2008/WD-html5-20080610/dom.html#innerhtml0 and http://www.whatwg.org/specs/web-apps/current-work/multipage/content-models.html#innerhtml.



And since there seems to be a bit of an innerHTML vs. createElement discussion going on, I want to clarify that my use of the expression "DOM manipulation" includes both of those.

Philip M
08-27-2011, 04:03 PM
For my personal perception the DOM way of creating and appending elements is cleaner than the innerHTML way. .

I don't want to prolong this, but most people consider that innerHTML is much faster and much less verbose than the DOM manipulation method.

VIPStephan
08-27-2011, 04:19 PM
I don't want to prolong this, but most people consider that innerHTML is much faster and much less verbose than the DOM manipulation method.

OK, you're entitled to an opinion like anyone else and nothing of what you think of my posts can possibly be of interest, let alone of consequence to me.. :p :D ;)

DanInMa
08-27-2011, 05:30 PM
someone got stood up last night.

webdev1958
08-28-2011, 12:19 AM
...but most people consider that innerHTML is much faster and much less verbose than the DOM manipulation method.

What is the point you are trying to make in reply to VIPStephan's comment


For my personal perception the DOM way of creating and appending elements is cleaner than the innerHTML way.

because earlier you said


Yes, I agree that DOM methods including createElement(), appendChild() etc. should be used to create elements.

webdev1958
08-28-2011, 12:31 AM
innerHTML is part of both the W3C HTML5 specs and the WHATWG HTML Living Standard

The HTML5 specs are still being developed and so I don't take any notice of what's in them until they are final and officially recommended as a standard. I think you'll find what is currently in the draft might not all be there in the final specs, still a few years away.

Regarding WHATWG, I only take notice of what the W3C officially recommend.

Philip M
08-28-2011, 08:21 AM
You seem to be in a quarrelsome mood today.


yes even though innerHTML is not in the DOM specifications, it is supported by major browsers but it's not advisable to try to create elements with it.

And I agreed with that remark. None the less, innerHTML does have some advantages. As VIPStephan has said, "just agree to disagree as long as the aspirant JS developer is well informed about all possibilities, their advantages and drawbacks, so they can make their own decision what works best for them."

webdev1958
08-28-2011, 08:26 AM
Not at all :)

But it's interesting to see you are now prepared to agree to disagree since you can't post anything that shows anything I posted is not accurate or relevant and that a real moderator told you to "....just agree to disagree...." ;) which is what I told you indirectly when I said it's not up to you to decide for the op what is useful or not for them.

And given none of my suggestions to the op have been deleted by the moderators, it seems they do not agree with you either.

Philip M
08-28-2011, 08:37 AM
Any disagreement is entirely manufactured - by you. I do not see anything in my posts which claim that anything you said was either inaccurate or irrelevant. You seem to be yet another immature guy whose paranoia causes them to see everything as a threat, an insult, a challenge, a provocation, a rejection. I have the idea that you could go into an empty room and start an argument. :) Loosen up, please.

Asher01
08-28-2011, 08:41 AM
Firstly, thank you to everybody for their input and responses. My original question has been answered, plus given me probably answers to other questions I'd probably soon have.

My main worry was that most of the 'document.write' examples I had seen could of simply been done in HTML and the only other way I had seen a way to manipulate the HTML with JavaScript was 'document.getElementById()'.
However after seeing the posts about 'createElement(), appendChild() and innerHTML()' .. then using that to do a bit of Googling .. my worries seem put to rest a little.



Also, document.write only works with pages that the browser processes as HTML. Pages the browser processes as XML cannot use document.write at all.

However it should still be OK for XHTML, right?



There is no point in offering advanced level solutions to beginners

I would like to point out, that as long as it has been paid attention to that the OP (me) may only understand 'beginner level' solutions and a simple answer was provided to begin with... then there is nothing wrong with also giving a more detailed reasoning. As long as you realize you may be bordering on the OP's scope of the topic.



Considering the 'innerHTML()' though, I did a bit of reading up... it seems this was created by the dreaded Microsoft IE and later adopted by most other common browsers. While not originally in the W3C standard it is widely accepted and used because, apparently (I don't know yet) it's easier to use.
However... I am all for learning "the right way" first... so, are there any problems associated with using it?
Is it more of a case of what's "professionally correct" or "officially correct" ?

Again, thank you all for the responses.

webdev1958
08-28-2011, 08:45 AM
You seem to be yet another immature guy whose paranoia causes them to see everything as a threat, an insult, a challenge, a provocation, a rejection. I have the idea that you could go into an empty room and start an argument.
now look who is being quarrelsome...hehehe :)


I do not see anything in my posts which claim that anything you said was either inaccurate or irrelevantIn post 4 you said


There is no point in offering advanced level solutions to beginners.The solution I offered is not advanced :)

So since you can't post anything that shows my suggestion was "advanced" and the moderators haven't deleted my suggestion then we can agree to disagree and you can stop trying to decide for the op what is useful to them or not. It is up to them to decide and not you :)

Asher01
08-28-2011, 08:46 AM
While trying to remain impartial to the argument... I must agree to a point that Webdev just made about HTML5... I have totally ignored a lot to do with HTML5 as nothing is concluded yet and it would be pointless learning what you BELIEVE will be HTML5 approved if it hasn't been made official yet.
Which is partly why I decided to use XHTML as much as possible instead of HTML4... it's cleaner, and not hanging on the edge of changing.. as far as I know.

Philip M
08-28-2011, 09:08 AM
The OP said that "I am very new to JavaScript" . I remarked that "There is no point in offering advanced level solutions to beginners." You say that the solution you offered is not advanced. That is a matter of opinion (and you are quite entitled to your opinion - and so am I) in the context of "very new". Perhaps I should have said "relatively advanced". But I suspect that whatever was said you would search zealously for something to argue about.

My comments in Post#19 apply. Google for more information.

All I can say about innerHTML and HTML5 is that if it is not included in the final specification an awful lot of websites are going to need reworking.

webdev1958
08-28-2011, 09:10 AM
All I can say about innerHTML and HTML5 is that if it is not included in the final specification an awful lot of websites are going to need reworking.

why?

it's not in the html4 specs is it?

At w3schools (http://www.w3schools.com/htmldom/dom_methods.asp)it says


innerHTML is not a part of the W3C DOM specification.So unless w3schools is wrong in making that statement, your statement shows that your knowledge of javascript and general website development is at most at a basic level.

So if pages work now when innerHTML is not in the specs, then they will continue to work post-HTML5 whether it is included in the final HTML5 specs or not :)

Asher01
08-28-2011, 09:18 AM
All I can say about innerHTML and HTML5 is that if it is not included in the final specification an awful lot of websites are going to need reworking.


Not necessarily, if it's allowed in HTML4 and/or XHTML then all you would need to do is write using one of those and remember to use the Document Type Declaration... then you'll be fine.

webdev1958
08-28-2011, 09:18 AM
However after seeing the posts about 'createElement(), appendChild() and innerHTML()' .. then using that to do a bit of Googling .. my worries seem put to rest a little.

I would like to point out, that as long as it has been paid attention to that the OP (me) may only understand 'beginner level' solutions and a simple answer was provided to begin with... then there is nothing wrong with also giving a more detailed reasoning. As long as you realize you may be bordering on the OP's scope of the topic.

I did a bit of reading up... it seems this was created by the dreaded Microsoft IE and later adopted by most other common browsers. While not originally in the W3C standard it is widely accepted and used because, apparently (I don't know yet) it's easier to use.
However... I am all for learning "the right way" first... so, are there any problems associated with using it?
Is it more of a case of what's "professionally correct" or "officially correct" ?


glad to see my suggestion was of some help, at least as food for thought originally :)

The w3schools (not linked to the w3c though) is a handy resource and the owners are in the process of updating the information where it is a little out of date.

Whether you use innerHTML or DOM methods to create elements is up to you. Personally I always use DOM methods as there is no advantage in using innerHTML to create elements especially since in some cases it has caused problems for some members who ask for help.

Javascript still has to parse the innerHTML string and then probably uses its own core DOM methods to create the elements anyway :)

If you need more help, just post back :)

Philip M
08-28-2011, 10:58 AM
Whether you use innerHTML or DOM methods to create elements is up to you. Personally I always use DOM methods as there is no advantage in using innerHTML to create elements.


I agree entirely with that comment.

venegal
08-28-2011, 12:40 PM
While trying to remain impartial to the argument... I must agree to a point that Webdev just made about HTML5... I have totally ignored a lot to do with HTML5 as nothing is concluded yet and it would be pointless learning what you BELIEVE will be HTML5 approved if it hasn't been made official yet.
Which is partly why I decided to use XHTML as much as possible instead of HTML4... it's cleaner, and not hanging on the edge of changing.. as far as I know.

It's ultimately your choice, of course. Knowing what the WHATWG and the W3C HTML WG are about, there's no chance, though, that innerHTML could be removed from the final W3C specs. It would be completely insane.

Tails
08-28-2011, 11:39 PM
For tutorial sake and advanced debugging, alert() can often replace document.write() usefulness.

venegal
08-29-2011, 12:08 AM
For tutorial sake and advanced debugging, alert() can often replace document.write() usefulness.

For debugging purposes, it's usually better to use console.log().



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum