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

367
Visualizações
How can I highlight the inner text of an HTML article element by index with just vainilla js?

Let's say I have an HTML document with the following body:

<style>
  .highlighted {
    color: red;
    background-color: yellow;
  }
</style>

<article>My text in an element</article>

I have the challenge to style the i letter from the in word inside the <article> tag with javascript, and I'm required to do it by it's index [8]. So far I can only think of starting with this...

<script>
  const article = document.querySelector('article').innerText
  console.log(article[8]);
</script>

Expected output:

<article>My text <span class="highlighted">i</span>n an element</article>

// Console
>>>> "i"

...although I've never tried anything like this before, so I'm kinda lost with the following steps.

I supose I need to insert a <span> tag by this index, but I'm not sure how I would set the closing </span> tag or update the DOM.

What would be a good way to achieve this kind of styling?

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

0

const HIGHLIGHT_IDX = 8;
const article = document.querySelector('article').innerText;
const words = article.split(' ');
let highlightCheck = words[0].length;
let wordToHighlight = words[0].length >= HIGHLIGHT_IDX && '0';
let wordIdx = 1;

while (!wordToHighlight) {
  highlightCheck += 1 + words[wordIdx].length;
  if (highlightCheck >= HIGHLIGHT_IDX) {
    wordToHighlight = wordIdx;
  } else {
    wordIdx += 1;
  }
}

words[wordToHighlight] =
  `<span class="highlight">${words[wordToHighlight]}</span>`;

document.querySelector('article').innerText = words.join(' ');
about 4 years ago · Juan Pablo Isaza Relatório

0

//get text of article
const article = document.querySelector('article').innerText;

//find index of word 'in'
const index = article.indexOf('in');

//opening and closing tags
const openingTag = '<span style="color:red">'
const closingTag = '</span>'

//insert tags into article
const newHTML 
  = article.slice(0, index) 
  + openingTag + 'in' + closingTag 
  + article.slice(index + 2);
document.querySelector('article').innerHTML = newHTML;

This code styles the first occurrence of the word "in" by setting the text color to red. If you want to do something else, change the style attribute of the opening tag.

article.slice(0, index) returns everything before the word "in." In your example, this would evaluate to 'My text '. article.slice(index + 2) returns everything after the word "in" because "in" is 2 letters long. In your example, this would evaluated to ' an element'. When all the strings are concatenated together, the result is 'My text <span style="color:red">in</span> an element'.

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