Sameeksha Kumari
Sameeksha Kumari

Reputation: 1264

document.write to display content on same page

I have a doubt with JavaScript document.write method. Mostly when I use document.write() it shows me the content written with the method in a different page. For instance, if I write the command like this, document.write("Hello, My name is Sameeksha"); then the execution of this line takes me to a different document on the same page. I want to be able to append the message on the same page, with other elements of the page. For example, if I have text boxes and buttons on the page and I want the text with document.write to appear under all the content of the page or on a particular section of a page. Please suggest what can be done to get the output in this way? As, this way it will be really easy to create dynamic HTML content.

Upvotes: 2

Views: 17173

Answers (2)

DaoWen
DaoWen

Reputation: 33019

I'd say 6502 posted the more correct way to do it, but I think someone should mention innerHTML as well. First, give some element in your HTML body an id so you can reference it:

<div id="outputDiv">I'm empty.</div>

Then, either at the bottom of your document (at the end of the <body> tag), or any other time after the page is loaded, you can update the contents with innerHTML:

document.getElementById("outputDiv").innerHTML = "<h1>Hello!!!</h1>";

Here's a jsfiddle demonstrating this. This isn't as clean/correct/elegant as using the more standard DOM methods, but it's well supported. Sometimes quick and dirty is what you need!

Upvotes: 2

6502
6502

Reputation: 114461

document.write is basically never used in modern Javascript.

Whan you do instead is to create explicit DOM elements and append them to the document in the place you want. For example

var x = document.createElement("div");  // Creates a new <div> node
x.textContent = "Hello, world";         // Sets the text content
document.body.appendChild(x);           // Adds to the document

Instead of appending to the end you can also add child nodes to any existing node. For example:

function addChatMessage(msg) {
    var chat = document.getElementById("chat"); // finds the container
    var x = document.createElement("div");
    x.textContent = msg;
    chat.appendChild(x);
}

Upvotes: 7

Related Questions