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

366
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 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