swagless_monk
swagless_monk

Reputation: 471

Highlighting Words That Fit a Specific Criteria

I have some simple code below but I am failing to see the results.

Essentially, I have some static text in a div with class="container" I'm trying to apply a function to this div to highlight any word that begins with a specified letter, in this case the start letter = "t". Then return the new text (with highlights) to the original div.

What am I doing wrong here?

//highlight ANY word that starts with t

function highlighter(text) {
  text = text.split()
  for (var i = 0; i < text.length; i++) {
    if (text[i][0] == 't') {
      text[i] = "<mark style='background-color:red; color:white;'>" + text[i] + "</mark>";
    }
  }
  return text
}
<div class="container" onclick=highlighter( "This is a simple test to see how the function will perform.")>
  This is a simple test to see how the function will perform.
</div>

Upvotes: 1

Views: 44

Answers (1)

Chris
Chris

Reputation: 391

In your example you compute the output, but don't actually set it:

<!DOCTYPE html>
<html>
  <body>

    <div class="container" onclick="highlighter(this)">
    This is a simple test to see how the function will perform.
    </div>

    <script>
//highlight ANY word that starts with t

function highlighter(ev) {
        var content = ev.innerHTML;
        var tokens = content.split(" ");
        for (var i = 0; i < tokens.length; i++) {
                if (tokens[i][0] == 't') {
                        tokens[i] = "<mark style='background-color:red; color:white;'>" + tokens[i] + "</mark>";
                      } 
              }
        ev.innerHTML = tokens.join(" ");
}
    </script>

  </body>
</html>

Upvotes: 1

Related Questions