简体   繁体   中英

Setting HTML Style Using Javascript String Literal - Colon Breaks String Variable

I'm trying to set the style on an HTML element before appending it to the page by passing the style tag through a variable in a JavaScript string literal.

So my code looks like this:

const STYLE = "font-weight: bold; color: crimson; background-color: red;"
const item = `<p class="text" style=${STYLE}>Some Text</p>`
const position = "beforeend";
list.insertAdjacentHTML(position, item);

When I run it though, the HTML on the page looks like this - the quotation mark on the style tag ends after the first colon. Is there any way to get the full string into the style tag?

<p class="text" style="font-weight:" bold; color: crimson; background-color: red;>Some Text</p>
const item = `<p class="text" style=${STYLE}>Some Text</p>

You should wrap ${STYLE} with ":

const item = `<p class="text" style="${STYLE}">Some Text</p>

Browsers for attributes values without " are adding them themselves and closing them before the first space in the string. That's why "font-weight:" was wrapped here:

style="font-weight:" bold; color: crimson; background-color: red;>

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