0

Here is the function:

function funct1()
{
    document.getElementById("demo").innerHTML="Something";
    document.write("Mexico!");
}

The output is only:

Mexico

when I click the button on the page, whereas I wanted the output to be:

Something
Mexico
Ian
  • 50,146
  • 13
  • 101
  • 111
  • 5
    When you call `document.write()` after the page is shown, the whole page will be overwritten. – Pointy Feb 18 '13 at 15:31

2 Answers2

2

In this instance document.write() doesn't do what you think. It clears the contents of the document, and writes Mexico! (see Quentin's answer for a more detailed explanation of why that is). If you remove this line, you can see that your first statement is executed correctly.

If you want to update the first paragraph, and also add another, you should use the following code:

function funct1()
{
    document.getElementById("demo").innerHTML = "Something";  

    // Create a new <p> element, set its HTML and then append it:
    var newP = document.createElement('p');
    newP.innerHTML = 'Mexico!';
    document.body.appendChild(newP);
}

You can see a working jsFiddle here.

BenM
  • 52,573
  • 26
  • 113
  • 168
  • You might want to mention that `document.write` doesn't naturally "clear the contents of the document". It's the fact that the document has been closed that it does this. – Ian Feb 18 '13 at 15:34
  • 1
    Thanks Ian, updated with a little more information that actually answers the question :) – BenM Feb 18 '13 at 15:37
2

After setting the innerHTML of demo, you call document.write. Since the document is in a closed state at this time, this makes an implicit call to document.open which erases the entire existing document (including the stuff you just assigned with innerHTML). Then you write Mexico! to the new document.

Never call document.write after the DOM is ready (and avoid doing so at any other time). Use DOM manipulation instead.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335