Search code examples
javascriptbackground-colordocument-body

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";
    })();

Solution

  • 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";
               }
            }
         })();