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

Why do we need HTML tags in JavaScript?

Why do we need HTML tags? Code seems to work without them just fine.

For example:

document.write("<p>The tags won't show up, but this text will.</p>");
document.write("This text will show up, too!");

2 Answers

Hey Yan,

Using HTML tags along with document.write() (and in other circumstances) allows you to push elements out to the page. The difference between using HTML elements in your methods and just using plain text is that with the HTML elements you'll have major control over the style and interactivity of the text. You can add an id/classes/other attributes to the text which can all enhance the text and also enhance the user experience.

If, however, you just use plain text such as "This text will show up, too!", you don't have nearly as much control over the text. And, especially when using document.write(), the text will all be scrunched together unless you write in some <br> elements or newline characters "\n". And it will always be in black ink on a white background when using document.write(). Using plain text is just plain boring :)

My understanding is that it 'writes' to the html document. That means the browser 'sees' what you add as html and takes the tags into consideration.. So if you left out the <p></p> the added text wouldn't be in it's own 'container'

You could have done <div> or <h1> or whatever you wanted the added text to be.

you see a lot more of this with Jquery where you are using a library of javascript functions designed to change things inside the hmtl document