Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Basics (Retired) Storing and Tracking Information with Variables The Variable Challenge Solution

Using HTML tag within JavaScript String

It seems that HTML tag is being used within a string. It seems when HTML tag is used within a string it is still considered as a tag. (This concept was not introduced earlier)

for example:

var message = '<h1>A test string</h1>'

Will produce "A test string" with H1 CSS formating.

I'm wondering why doesn't it consider the tags inside the quotation mark as strings? Also what is the way to show HTML mark-up as strings?

3 Answers

Dave McFarland
Dave McFarland
Treehouse Teacher

Bappy Golder

JavaScript sees this -- '<h1>A test string</h1>' -- as a string, but when you use the document.write() method, the web browser CONVERTS the string into HTML.

You can test this yourself with alert('<h1>A test string</h1>'). You'll see the string in the alert box is not a rendered tag.

Dave McFarland

I did tried both console.log and alert. it's good the see the differences in behaviour in JavaScript.

The variable is still a string, but just has HTML markup surrounding the text. If you were to print this variable out in a browser, the browser will respond to the HTML formatting present in the string. To just print the HTML, surround the content with the PRE tag:

<h1>Show raw HTML</h1>
Pavle Lucic
Pavle Lucic
10,801 Points

When you adding html tags in some string , and later you use that string to place it on webpage, browser will render that piece of code, the same as you would write in html file.

The concept is next, when you start to create your web application, you will add dynamic html content, using javascript.