0

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>

1 Answer 1

3
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;>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.