Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

135
Visualizações
i want the function of for loop to perform one by one when a key or mouse is pressed
<div id="text">Nature in the broadest sense is the physical world or universe</div>
let el = document.getElementById(text);
let eltext = el.innerText;
let final = eltext.split(" ");
let i;
for (i = 0; i < final.length; i++) {
 if (final[i] === "the") {
   final[i] = `<b>${final[i]}</b>`;
 }
let result = (final + " ").replace(/,/g, " ");
el.innerHTML = result;

the result will be: Nature in the broadest sense is the physical world or universe

what i want: when any key is triggered for the first time: Nature in the broadest sense is the physical world or universe

when any key is triggered for the second time: Nature in the broadest sense is the physical world or universe

when any key is triggered for the third time again: Nature in the broadest sense is the physical world or universe

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Rather than for loop, I'd recommend you use built-in Array methods for better readability. Here I've extended your sample sentence to show how it can accommodate for longer sentences with more target words.

const text = document.querySelector('#text').innerText.split(' ');
const indices = text.map((word, index) => word === 'the' ? index : 0)
  .filter(i => i !== 0);
  
let highlightIndex = 0;

function toggle() {
  const arr = [...text];
  arr[indices[highlightIndex]] = `<strong style="color: red;">${arr[indices[highlightIndex]]}</strong>`;
  document.querySelector('#text').innerHTML = arr.join(' ');
  highlightIndex += 1;
  if (highlightIndex > indices.length -1 ) highlightIndex = 0;
}

window.addEventListener('keydown', toggle);
window.addEventListener('click', toggle);
<div id="text">Nature in the broadest sense is the physical world or universe. Introduce the article here for testing the code.</div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda