Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
172
rated 0 times [  173] [ 1]  / answers: 1 / hits: 16234  / 11 Years ago, sat, july 27, 2013, 12:00:00

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.
Thank you so much for your time.



Regards,
Sameeksha Kumari


More From » javascript

 Answers
12

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);
}

[#76706] Friday, July 26, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zachary

Total Points: 175
Total Questions: 89
Total Answers: 108

Location: Fiji
Member since Wed, Jul 14, 2021
3 Years ago
;