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

430
Visualizações
Changing the background color of text on a webpage in JavaScript (when element ID or name isn't available)

What I want to achieve is that once a web page is loaded, find some text in it and highlight the text. My code what I've written till now is as follows.

First I match the textContent using a regular expression (Why am I using this approach is because I don't have the ID or name for the div where the textContent is present, thus, I cant go for getElementsByName() or getElementById()). To check if the text exists, I first compare it's length and then proceed to highlight it.

The text I find is at index 0 of the text variable. I cant access backgroundColor() method that is why it's been commented out for now. I could access fontcolor() but even it didn't seem to work.

I am new to JS so some direction would be greatly appreciated.

  • I would like to know why fontcolor() doesn't work even though I can access it.
  • What would be the best approach to solve this as I cant access backgroundColor().
(function highlightText(){ 
   let text = document.body.textContent.match(/abcxyz/);
   if (text[0].length == 6)
   {
      text[0].fontcolor('yellow');
      //text[0].backgroundColor('yellow');
      console.log(text[0]);                //prints abcxyz
      return text[0];
   }
   return null;
})()

SOLUTION: The approach based off on the solution provided by @forlen:

What I did was loop through all the nodes, if the textContent matches the regular expression then push them into an array and as I knew what I wanted was the root element so I got the last element of the array and changed its backgroundColor.

    (function highlightText() {
        let allNodes = document.body.getElementsByTagName("*");
    
        var arr= [];
        for (let node of allNodes) {
           if (node.textContent.match(/abcxyz/)) {
               arr.push(node);
           }
        }
    
        text = arr[(arr.length)-2];
        text.style.backgroundColor = "yellow";
    })();
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I recommend looping through all nodes in body and changing style like this:

(function highlightText() {
        let allNodes = document.body.getElementsByTagName("*");

        for (let node of allNodes) {
           if (node.textContent === "abcxyz") {
              node.style.color = "yellow";
           }
        }
     })();
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