using the DOM to add elements, document.write

flipflopmedia picture flipflopmedia · Mar 3, 2010 · Viewed 12.4k times · Source

I have just learned (no thanks to IE) that I cannot use document.write scripts in XHTML. However, it seems there is a way around it by using the DOM to add elements. I don't know. It's foreign to me.

Here's the JS:

copyright=new Date();
update=copyright.getFullYear();
document.write("Copyright © 2004-"+ update + " flip-flop media");

So, is there a way to use this script in XHTML? IE 8 shows an empty space with an error warning. IE 7 shows just the warning. FF does display it properly.

And it shows up with no errors and displays properly on one of my pages: http://clients.flipflopmedia.com

But not on the main page: http://www.flipflopmedia.com/NewSite/index.html

Answer

David Murdoch picture David Murdoch · Mar 3, 2010

To answer your question: The will append a copyright notice as the last element on the page.

(function(){
    // create almost any element this way...
    var el = document.createElement("div");
    // add some text to the element...
    el.innerHTML = "Copyright © 2004-"+ (new Date).getFullYear() + " flip-flop media";
    // "document.body" can be any element on the page.
    document.body.appendChild(el);
}());

You can always change "document.body" to whatever element you want to use. Such as document.getElementById("copyright").appendChild(el);

jQuery

You already have jQuery on the page. So just use:

$(function(){
    // "body" is a css selector.
    // you can use almost any css selector 
    // to find the element you need. e.g. $("#copyright")...
    $("body").append("Copyright © 2004-"+ (new Date).getFullYear() + " flip-flop media");
    // you can also use html() to replace the existing content.
    // $("#copyright").html("content goes here");
});

What you should do:

Use server-side technologies like php, .net, etc.

You probably are running php on your server which means the following should work anywhere in your page (if it has a php extension (index.php instead of index.html), of course):

<?php
    echo 'copyright &copy; 2004-' + date("Y") . ' flip-flop media';
?>