Web Analytics Made Easy -
StatCounter Alternative to 'document.write()' ?? - CodingForum

Announcement

Collapse
No announcement yet.

Alternative to 'document.write()' ??

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Alternative to 'document.write()' ??

    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
    “Opinion is the medium between knowledge and ignorance.”
    “The old believe everything; the middle aged suspect everything: the young know everything.”

  • #2
    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:-

    Code:
    <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
    Last edited by Philip M; Aug 27, 2011, 08:03 AM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

    Comment


    • #3
      Originally posted by Asher01 View Post
      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:

      Code:
      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.
      Last edited by webdev1958; Aug 27, 2011, 08:11 AM.

      Comment


      • #4
        Originally posted by webdev1958 View Post
        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.
        Last edited by Philip M; Aug 27, 2011, 08:27 AM.

        All the code given in this post has been tested and is intended to address the question asked.
        Unless stated otherwise it is not just a demonstration.

        Comment


        • #5
          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.

          Comment


          • #6
            Originally posted by webdev1958 View Post
            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.

            All the code given in this post has been tested and is intended to address the question asked.
            Unless stated otherwise it is not just a demonstration.

            Comment


            • #7
              Originally posted by Philip M View Post
              But here were are talking about inserting a value into an existing element.
              I suppose you mean the "were" is actually just you

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

              Originally posted by Philip M View Post
              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.
              Last edited by webdev1958; Aug 27, 2011, 09:38 AM.

              Comment


              • #8
                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?

                Comment


                • #9
                  Originally posted by Asher01 View Post
                  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 ....
                  Code:
                  <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.
                  Last edited by DaveyErwin; Aug 27, 2011, 10:23 AM. Reason: careless omition of script tag

                  Comment


                  • #10
                    Originally posted by DaveyErwin View Post
                    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.
                    Stop solving problems you don’t yet have!

                    Comment


                    • #11
                      Originally posted by Asher01 View Post
                      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.


                      Originally posted by webdev1958 View Post
                      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-2...tml#innerhtml0 and http://www.whatwg.org/specs/web-apps...html#innerhtml.


                      Edit:
                      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.
                      Last edited by venegal; Aug 27, 2011, 12:10 PM.
                      .My new Javascript tutorial site: http://reallifejs.com/
                      .Latest article: Calculators — Tiny jQuery calculator, Full-fledged OOP calculator, Big number calculator
                      .Latest quick-bit: Including jQuery — Environment-aware minification and CDNs with local fallback

                      Comment


                      • #12
                        Originally posted by VIPStephan View Post
                        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.

                        All the code given in this post has been tested and is intended to address the question asked.
                        Unless stated otherwise it is not just a demonstration.

                        Comment


                        • #13
                          Originally posted by Philip M View Post
                          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..
                          Stop solving problems you don’t yet have!

                          Comment


                          • #14
                            someone got stood up last night.
                            - Firebug is a web developers best friend! - Learn it, Love it, use it!
                            - Validate your code! - JQ/JS troubleshooting
                            - Using jQuery with Other Libraries - Jslint for Jquery/other JS library users

                            Comment


                            • #15
                              Originally posted by Philip M View Post
                              ...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

                              Originally posted by Philip M View Post
                              Yes, I agree that DOM methods including createElement(), appendChild() etc. should be used to create elements.

                              Comment

                              Working...
                              X