amir
amir

Reputation: 69

Grouping text colors in CSS

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 ?

Upvotes: 0

Views: 136

Answers (2)

Udochukwu Enwerem
Udochukwu Enwerem

Reputation: 2823

Mind you, elements can have multiple classes:

<h1 class="custom-color h1"></h1>
<td class="custom-color tdform"></td>
<form class="custom-color textForm"></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";
}

Upvotes: 0

Mirco Bellagamba
Mirco Bellagamba

Reputation: 1218

There are 2 ways to do that.

  1. 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 class="container">
  <h2>Title</h2>
  <p>Paragraph</p>
  <button id="color-toggle">Toggle Color</button>
</div>

  1. 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 class="container">
  <h2 class="title">Title</h2>
  <p class="paragraph">Paragraph</p>
  <button id="color-toggle" class="button">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.

Upvotes: 2

Related Questions