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 trialBappy Golder
13,449 PointsUsing 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
Treehouse TeacherJavaScript 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.
miguelcastro2
Courses Plus Student 6,573 PointsThe 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:
<pre>
<h1>Show raw HTML</h1>
</pre>
Pavle Lucic
10,801 PointsWhen 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.
Bappy Golder
13,449 PointsBappy Golder
13,449 PointsDave McFarland
I did tried both console.log and alert. it's good the see the differences in behaviour in JavaScript.