I have a webpage with css, and some text colors in this css :
h1 {
color:red;
}
.tdform {
color:red;
..
}
.textform, .passform, .buttonform {
color:red;
..
}
..
I wish to change this structure to can have access to all these colors (for changing them) through a single line javascript call, in the style :
document.getElementByXYZ('newElement').color = blue;
And not :
document.getElementsByClassName('h1').style.color = blue;
document.getElementsByClassName('tdform').style.color = blue;
document.getElementsByClassName('textform').style.color = blue;
...
What is please the best way ?
CodePudding user response:
There are 2 ways to do that.
- Cascading: you can set the text color on a parent element and inner elements will inherit this value.
document.getElementById('color-toggle').addEventListener('click', e => {
document.querySelector('.container').classList.toggle('green');
});
.container {
color: red;
}
.container.green {
color: green;
}
.container button {
color: inherit
}
<div >
<h2>Title</h2>
<p>Paragraph</p>
<button id="color-toggle">Toggle Color</button>
</div>
- CSS Custom properties: you can define CSS variable and use that instead of directly using the value.
document.getElementById('color-toggle').addEventListener('click', e => {
document.querySelector('.container').classList.toggle('green');
});
:root {
--text-color: red;
}
.container.green {
--text-color: green;
}
.title {
color: var(--text-color);
}
.paragraph {
color: var(--text-color);
}
.button {
color: var(--text-color);
}
<div >
<h2 >Title</h2>
<p >Paragraph</p>
<button id="color-toggle" >Toggle Color</button>
</div>
In the example above CSS Custom Properties are used in combination with Cascading. You can also directly update CSS Variables from Javascript.
CodePudding user response:
Mind you, elements can have multiple classes:
<h1 ></h1>
<td ></td>
<form ></form>
The most straight forward and efficient way to change all their colors together is to use their common class. That's the essence of css classes:
for (var e of document.querySelectorAll(".custom-color")) {
e.style.color = "red";
}