简体   繁体   中英

Why doesn't document.write work on a variable with HTML tags?

document.write on a variable works fine. document.write on a string with HTML tags also works fine. However, when trying to use document.write on a JS variable with HTML tags, the program doesn't work.

Here's my code:

var Foo = "Foo Variable"
document.write(Foo)
document.write("<h1>Foo</h1>");
document.write(<h1>Foo</h1>)

The first three lines work fine, but the last line doesn't display anything. I believe this is a syntax error, but no matter what I try it still doesn't seem to work. I've tried putting just the HTML tags in quotes with no avail. Is there any way for me to have a string variable expressed as a header? In other words, I want the page to display the words "Foo Variable" as an h1 header.

Thanks in advance.

Yes, it's a syntax error. If you want to output the contents of the Foo variable within h1 tags, you need to use a template literal (ES2015+) or string concatenation:

// Template literal (ES2015+)
var Foo = "Foo Variable";
document.write(`<h1>${Foo}</h1>`);

or

// String concatenation
var Foo = "Foo Variable";
document.write("<h1>" + Foo + "</h1>");

But , there's almost no place for document.write in modern web programming. Instead, use the DOM to add or update elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM