JSFiddle - React, Tailwind, and code Playground

by Lalji Tadhani

HTML

<input id="search" type="text" placeholder="Search" />
<div class="post">Long long</div>

CSS

.highlight {
  background: yellow;
}

JavaScript

$('#search').on('keyup', function(event) {
  var keyword = event.currentTarget.value;
  highlight('.post', keyword);
});

function highlight(selector, keyword) {
  $(selector).each(function(index, element) {
    var $element = $(element);
    var original = $element.data('originalText');
    if (original == undefined) {
      original = $element.html();
      $element.data('originalText', original);
    }
    $element.html(original.replace(keyword, '<span class="highlight">' + keyword + '</span>'));
  });
}