Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

131
Vistas
How to change the color of last Element in array - js

I have a problem in my following Code:

let textPos = document.getElementById('js-headline');
let i = 0;

function typewriter() {
  let letters = ['C', 'o', 'd', 'e', 'X'];
  if (i < letters.length) {
    textPos.innerText += letters[i];
    i++;
    setTimeout(typewriter, 1000);
  } else if (i == letters.length) {
    let lastLetter = letters[letters.length - 1];
    lastLetter.style.color = 'red';
  }
}

typewriter();

in my "else if" I select the last element of my array and I like to change the color but it doesn't work - I get an error message

"Uncaught TypeError: Cannot set properties of undefined (setting 'color')".

And one thing is crazy, I can put the last element of this array in an alert Box or in a console.log and it shows me the last element...

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You're trying to set the .style.color property of a string, which is impossible. You need to make a <span> element to be able to change the color, and add the <span> instead of the letter itself.

Also, your conditionals for finding the last element is wrong, so I fixed that too.

let textPos = document.getElementById("js-headline");
let i = 0;
function typewriter() {
        let letters = ["C", "o", "d", "e", "X"];
        if(i < letters.length - 1) {
        textPos.innerText += letters[i];
        i++;
        setTimeout(typewriter, 1000);
    }
    else {
        let lastLetter = letters[letters.length - 1];
        let span = document.createElement("span");
        span.innerText = lastLetter;
        span.style.color = "red";
        textPos.appendChild(span);
    }
}
typewriter();
<h1 id="js-headline"></h1>

about 4 years ago · Juan Pablo Isaza Denunciar

0

The positioning of array items starts from 0 so when you say i == letters.length that property doesn't exist of array the last index on array is equal to letters.length - 1

you need to change the code to following:

let textPos = document.getElementById('js-headline');
let i = 0;

function typewriter() {
  let letters = ['C', 'o', 'd', 'e', 'X'];
  if (i < letters.length - 1) {
    textPos.innerText += letters[i];
    i++;
    setTimeout(typewriter, 1000);
  } else if (i == letters.length - 1) {
    let lastLetter = letters[letters.length - 1];
    lastLetter.style.color = 'red';
  }
}

typewriter();

I hope it helped

Edit:

a little more about array indexing

for example in the following array the indexing is like below:

var array = ['a', 'b', 'c', 'd', 'e']
              ^    ^    ^    ^    ^
              |    |    |    |    |
              0    1    2    3    4

when you call array.length it will return the number of elements in array but the first index starts from 0

about 4 years ago · Juan Pablo Isaza Denunciar

0

I hope this demonstration of an alternative typewriter function helps!

async function typewrite(word, ele) {
  const letters = [...word];
  const lastLetter = letters.pop();
  for (letter of letters) {
    ele.textContent += letter;
    await new Promise(r => setTimeout(r, 500));
  }
  const aSpan = document.createElement("span");
  aSpan.style.color = "red";
  aSpan.textContent = lastLetter;
  ele.appendChild(aSpan);
}

typewrite("Hello World!", document.querySelector("#output"));
<div id="output"></div>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda