JSFiddle - React, Tailwind, and code Playground

by bob90937

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<table class="gridtable" border="1"> 
<tbody>
<tr>
    <th>sentence</th>
    <th>content</th>

  </tr>

<tr>
<td id="sentence">a paragraph</td>
<td id="content">And this here  is inside a paragraph , about paragliders.happy ending.</td> 
<tr>
<td id="sentence">unless they were granted</td>
<td id="content">All Singaporean children of school-going age are required to regularly attend a national primary school, unless they were granted an exemption due to physical or intellectual disabilities.</td> 
<tr>
<td id="sentence">efforts to</td>
<td id="content">MOE said that the change is part of the Government ongoing efforts to build a more inclusive society.</td> 
</tr>
</table>

CSS

.highlighted {
  background: yellow
}

JavaScript

$(document).ready(function() {

  var wordText = $('#sentence').text();
  var rootText = $('#content').text();
  var rootNode = document.getElementById('content');

  highlightWord(rootText, wordText);

  function highlightWord(rootText, wordText) {

    textNodesUnder(rootNode).forEach(highlightWords);

    function textNodesUnder(rootNode) {
      var walk = document.createTreeWalker(rootNode, NodeFilter.SHOW_TEXT, null, false);
      var text = [],
        node;
      while (node = walk.nextNode()) text.push(node);

      return text;
    }

    function highlightWords(n) {
      for (var i;
        (i = n.nodeValue.indexOf(wordText, i)) > -1; n = after) {
        var after = n.splitText(i + wordText.length);
        var highlighted = n.splitText(i);
        var span = document.createElement('span');
        span.className = 'highlighted';
        span.appendChild(highlighted);
        after.parentNode.insertBefore(span, after);
      }
    }
  }

});