Search code examples
javascriptarrayshighlight

Highlight text on page if matching text exist in array


I'm trying to highlight the text on the page if it matches the text in my array. The goal is to highlight the duplicates on the page.

var iterator = document.evaluate('xpathgoeshere', document, null, XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null);

try {
  var thisNode = iterator.iterateNext();
  var arrayList = [];

  while (thisNode) {
    arrayList.push(thisNode.textContent); 
    thisNode = iterator.iterateNext();
  }

  console.log(arrayList);

  for (var i = 0; i < arrayList.length; i++) {
    console.log(arrayList[i]);
  }   
} catch (e) {
  dump('Error: Document tree modified during iteration ' + e);
}

var arrayListDupes = arrayList.slice().sort();
var results = [];
for (var i = 0; i < arrayListDupes.length - 1; i++) {
    if (arrayListDupes[i + 1] == arrayListDupes[i]) {
    //while (results) {
        results.style.outline = "5px dashed red"; // I am probably doing
        results = iterator.iterateNext(); // it completely incorrect
        results.push(arrayListDupes[i]);
    }
}

console.log(results);

Solution

  • Use you existing code with the below function.

    var TRange=null;
    
    function findString (str) {
     if (parseInt(navigator.appVersion)<4) return;
     var strFound;
     if (window.find) {
    
      // CODE FOR BROWSERS THAT SUPPORT window.find
    
      strFound=self.find(str);
      if (!strFound) {
       strFound=self.find(str,0,1);
       while (self.find(str,0,1)) continue;
      }
     }
     else if (navigator.appName.indexOf("Microsoft")!=-1) {
    
      // EXPLORER-SPECIFIC CODE
    
      if (TRange!=null) {
       TRange.collapse(false);
       strFound=TRange.findText(str);
       if (strFound) TRange.select();
      }
      if (TRange==null || strFound==0) {
       TRange=self.document.body.createTextRange();
       strFound=TRange.findText(str);
       if (strFound) TRange.select();
      }
     }
     else if (navigator.appName=="Opera") {
      alert ("Opera browsers not supported, sorry...")
      return;
     }
     if (!strFound) alert ("String '"+str+"' not found!")
     return;
    }
    

    Try calling like findString (results[0]) , the text should highlight in the page.

    findString() source and demo here