Q: child span doesn't change the color although the parent is changed I want to dynamically change the color of whole span and its child using a function like this:


setTimeout(() => color(), 2500); 

function color() {
  const el = document.getElementById('expand');
  el.style.WebkitTransition = 'color 2s ease-in-out';
  el.style.color = '#9dde07';
}
.colored { 
  color: #fc0303; 
}
<span id="expand">  This forest 
<span class="colored">is</span> 
beautiful.
</span>


As you see although I change the parent span's color successfully but the child span does'nt change the color...
I know I can select the child span and try to do the same with it but the child span itself added dynamically and we don't have it always... So we need to check if it exist and try to change the color...
So the desired result is to change the whole text color to green using the function.
I wonder if there is a better solution to do this?

A: You can dynamically create a new CSS rules and apply the color to the elements and all the childs. This will work for any kind of combination:


const {sheet} = Object.assign(document.head.appendChild(document.createElement("style")), {type: "text/css" });


setTimeout(() => color(), 2500); 

function color() {
  const el = document.getElementById('expand');
  sheet.rules[sheet.insertRule("#expand,#expand * {transition:color 2s ease-in-out;color:#9dde07!important}")];
}
.colored { 
  color: #fc0303; 
}
<span id="expand">  This forest 
<span class="colored">is</span> 
beautiful
<span class="colored">and</span> 
big.
</span>


