Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Basics (Retired) Making Decisions with Conditional Statements Introducing Conditional Statements

I've read a lot lately saying the use of document.write (DW) is now bad form. Is this true & what's the alternative??

Most of what I've read & heard lately, including on sites like StackOverflow & the MDN, is that the use of the document.write method for printing output in a page is now frowned upon & its use it is best left for testing & debugging code. From what I understand, using document.write after an HTML document is fully loaded, will delete all existing HTML, which definitely sounds problematic..... Does anyone have an opinion on this &/or any suggestions as to the best alternative method??

Paolo Scamardella
Paolo Scamardella
24,828 Points

As far as I know, don't use document.write. An alternative way to write to the document, use DOM manipulation techniques to add elements to the DOM.

2 Answers

Hey Alexis,

document.write is really only useful in a test script, where nothing else is going to be output to the page as it does overwrite all previous content, as you mentioned. When doing debugging, I would use console.log if you're using Firefox or Chrome or just an alert if you're using another browser that doesn't have a web console.

As far as outputting content to the page, it's best to set up some kind of output element, and then output your data there. When using plain JavaScript, it is much faster to just use textContent method for inserting text into an element than it is to use innerHTML. You should only use innerHTML if you're inserting other HTML elements into another element. Here is a JS performance test showing how much faster textContent is versus innerHTML.

As Dmitriy mentioned, if you're using jQuery in your projects familiarize yourself with the html() and append() methods in jQuery. You can see live examples of them at the api.jquery.com website here.

If you ever have any questions, I or one of the many other helpful students and staff members here at Team Treehouse will help you! =]

Dmitriy Birioukov
Dmitriy Birioukov
684 Points

Don't use document.write it's considered as bad practice, do some research on jquery .append jQuery .html() and javascript innerHTML