0

I want to style element in javascript easily but this function doesn't work

const addStyles = function (el, styles) {
    Object.assign(el.style, styles);
}

1 Answer 1

1

You need to get the element first, then access the style property (it's a string) and set your CSS there.

Here's an example. As you can see the text is black and there is no CSS, however, with the javascript line I can make it red.

function addStyles(element, style) {
  element.style = style;
}


const myElement = document.getElementById("myText");

addStyles(myElement, "color: red; font-size: 25px;");
<p id="myText">Some text<p>

Sign up to request clarification or add additional context in comments.

3 Comments

I know that but I want sth like that ` addStyles(span, { width: "200px", height: "300px", background: "#fa00ff" });
it says: Uncaught TypeError: Failed to set an indexed property on 'CSSStyleDeclaration': Indexed property setter is not supported.
It means you're probably getting wrong the element. In the example above it works. Feel free to add more details in the question with your code.

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.