TheClassyCoder
TheClassyCoder

Reputation: 103

How do I change the style of a character in an array?

I have a div#effect in my HTML which of the text inside is written from the JavaScript I've put here,

I want to change the color of character "D" displayed in the div to be another color, I can refer to that character, console.log it or even alert it, but as soon as I want to set the style.color of it to say red, an undefined err pops,

how can I change the color of that specific character to another color?

let x = 0;
let textEffect = "Hi, \n I'm Dorothy, \n\ have a great day!".split('');
let container = document.getElementById("effect");

function animate() {
    if(x < textEffect.length){
        container.innerHTML += textEffect[x];
        x++;
        setTimeout(animate, 80);
    }  // here is the error : document.getElementById('effect').innerHTML.charAt(10).style.color = "red"
}
animate();
#effect {
  font-size: 2rem;
  font-weight: bold;
  line-height: 2rem;
  font-family: "Archivo Black", sans-serif;
  color: #e2e2e2;
  text-shadow: 1px 1px 10px #333333;
  height: 220px;
}
<div id="effect" style="white-space: pre-line;"></div>

<!-- begin snippet: js hide: false console: true babel: false -->

Upvotes: 1

Views: 625

Answers (1)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123367

document.getElementById('effect').innerHTML.charAt(10) will return a string and not a node object, so you can't apply a style method to this element

You need to wrap the 10th character of the string inside a span element

let x = 0;
let textEffect = "Hi, \n I'm Dorothy, \n\ have a great day!".split('');
let container = document.getElementById("effect");

function animate() {
    if (x < textEffect.length){
        if (x === 10) {
          container.innerHTML += '<span>' + textEffect[x] + '</span>';        
        }
        else {
          container.innerHTML += textEffect[x];
        }
        x++;
        setTimeout(animate, 80);
    } 
}
animate();
#effect {
  font-size: 2rem;
  font-weight: bold;
  line-height: 2rem;
  font-family: "Archivo Black", sans-serif;
  color: #e2e2e2;
  text-shadow: 1px 1px 10px #333333;
  height: 220px;
}

span {
 color: red 
}
<div id="effect" style="white-space: pre-line;"></div>

<!-- begin snippet: js hide: false console: true babel: false -->

Upvotes: 1

Related Questions