Can't update color of class dynamically.
By the way, the code works fine without having class, but on case having class, it does not work.
function myFunction() {
var cssColor=".MyClass h1{background-color:pink;color:black;} .MyClass p{background-color:pink;color:white;}";
cssColor = cssColor.replace('pink', document.getElementById("txtColor").value);
document.getElementById("mainBody").style.cssText = cssColor;
document.getElementById("mainBody").classList.add = cssColor;
document.getElementById('mainBody').className = 'MyClass';
}
<!DOCTYPE html>
<html>
<body id="mainBody" >
<h1>Title</h1>
<p >This is a paragraph.</p>
<input type="text" name="txtColor" id="txtColor" style="display: inline-block;width: 50px; height:30px;direction: ltr" maxlength="7">
<button type="button" onclick="myFunction()">Set style for p</button>
</body>
</html>
There are several problems with that code:
add
on classList
is a function, you don't assign to it, you call it:
document.getElementById('mainBody').classList.add('MyClass');
Your next statement assigns to className
, which will wipe out the call to classList.add
. So one of them or the other should be removed.
The .style.cssText
property on the body
element contains inline styles for body
, not a stylesheet. What you're assigning to it is stylesheet text. You'd put that in a style
element (or in a separate .css
file and link it with a link
element).
It's hard to help you with positive suggestions because it's not clear what you want to do. If you want to apply those styles to the page, updating pink
to the color the user inputs, you can have a style
element and update its text content. I wouldn't use pink
, though, I'd use some token like %%COLOR%%
. I'd also use modern event handling rather than an onclick
attribute, something along these lines:
var css =
"h1 { " +
" background-color: %%COLOR%%; " +
" color: black; " +
"} " +
"p { " +
" background-color: %%COLOR%%; " +
" color: white; " +
"}";
function setStyleToColor(color) {
document.getElementById("the-style").textContent = css.replace(/%%COLOR%%/g, color);
}
function myFunction() {
setStyleToColor(document.getElementById("txtColor").value);
}
setStyleToColor("pink");
document.querySelector("button").addEventListener("click", myFunction);
<style id="the-style"></style>
<h1>This is a heading</h1>
<p>This is a paragraph</p>
<input type="text" name="txtColor" id="txtColor" style="display: inline-block;width: 50px; height:30px;direction: ltr" maxlength="7">
<button type="button">Set style for p</button>
In a comment you've said:
I try to change color of my project
I would do that by having multiple separate stylesheets (pink.css
, blue.css
) and using a link
element to link them to the project. Updating the style becomes removing the old link and setting the new one.