Hi all,

I'm new to this and trying out a few projects to get started. What I want to do is get the script to search the page for keywords kept in one of three arrays and highlight the word in a colour depending on which array it is in. It's finding the words fine but instead of highlighting is just printing out the html to document;

First way I tried was;

s=s.replace(new RegExp(testArrayOne[j],'gi'),'<span style="color:#ff0000">' + testArrayOne[j] + '</span>');

I tried a second way using innerHTML which produced [object XPCNativeWrapper [object HTMLSpanElement]] instead of the html.

I should mention this is a userscript for greasemonkey and, as I say, I'm fairly new to this so I apologise if the answer is obvious.

Thanks for the help

Recommended Answers

All 2 Replies

using css with script as following example...

script :

function highlightOnLoad() {
  // Get search string
  if (/s\=/.test(window.location.search)) {
    var searchString = getSearchString();
    // Starting node, parent to all nodes you want to search
    var textContainerNode = document.getElementById("content");

    // Informational message for search
    var searchInfo = 'Search Results for: ';

    // Split search terms on '|' and iterate over resulting array
    var searchTerms = searchString.split('|');
    for (var i in searchTerms) 	{
      // The regex is the secret, it prevents text within tag declarations to be affected
      var regex = new RegExp(">([^<]*)?("+searchTerms[i]+")([^>]*)?<","ig");
      highlightTextNodes(textContainerNode, regex, i);
      // Add to info-string
      searchInfo += ' <span class="highlighted term'+i+'">'+searchTerms[i]+'</span> ';
    }

    // Create div describing the search
    var searchTermDiv = document.createElement("H2");
    searchTermDiv.className = 'searchterms';
    searchTermDiv.innerHTML = searchInfo;

    // Insert as very first child in searched node
    textContainerNode.insertBefore(searchTermDiv, textContainerNode.childNodes[0]);
  }
}

// Pull the search string out of the URL
function getSearchString() {
  // Return sanitized search string if it exists
  var rawSearchString = window.location.search.replace(/[a-zA-Z0-9\?\&\=\%\#]+s\=(\w+)(\&.*)?/,"$1");
  // Replace '+' with '|' for regex
  // Also replace '%20' if your cms/blog uses this instead (credit to erlando for adding this)
  return rawSearchString.replace(/\%20|\+/g,"\|");
}

function highlightTextNodes(element, regex, termid) {
  var tempinnerHTML = element.innerHTML;
  // Do regex replace
  // Inject span with class of 'highlighted termX' for google style highlighting
  element.innerHTML = tempinnerHTML.replace(regex,'>$1<span class="highlighted term'+termid+'">$2</span>$3<');
}

// Call this onload, I recommend using the function defined at: http://untruths.org/technology/javascript-windowonload/
addOnLoad(highlightOnLoad());

CSS:

span.highlighted {
  background-color: #161616;
  font-weight: bold;
}
span.term0 {
  background-color: #161633;
}
span.term1 {
  background-color: #331616;
}
span.term2 {
  background-color: #163316;
}

This

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <meta name="generator" content=
    "HTML Tidy for Windows (vers 25 March 2009), see www.w3.org">
    <script type="text/javascript">

function colorIt(){

    var term = document.getElementById('term').value

    var cSpns = document.getElementsByTagName('span')
    for (j = cSpns.length, i = 0; i < j; i++) {
        if (cSpns[i].firstChild.data == term) {
            cSpns[i].style.backgroundColor = cSpns[i].parentNode.getAttribute('id')
            cSpns[i].style.color = 'white'
        } else {
            cSpns[i].style.backgroundColor = 'white'
            cSpns[i].style.color = 'black'
        }
    }
}

    </script>
    <title></title>
  </head>
  <body>
    <form>
      <input id='term' onblur="colorIt()">
    </form>
    <div id='red'>
      <span>one</span><br>
      <span>two</span><br>
      <span>three</span>
    </div>
    <div id='green'>
      <span>top</span><br>
      <span>middle</span><br>
      <span>bottom</span>
    </div>
    <div id='blue'>
      <span>left</span><br>
      <span>center</span><br>
      <span>right</span>
    </div>
  </body>
</html>

shows one method.

It is a toy, so it makes some reasonable assumptions to simplify the coding.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.