JSFiddle - React, Tailwind, and code Playground
HTML
<div id="one">
<p>This is some highlighted text</p>
<p>Want some more light!</p>
</div>
<div id="two">
<p>This is some highlighted text</p>
<p>Want some more light!</p>
</div>
CSS
/* highlight is the default class added by the plugin */
.highlight{ background: yellow; }
/* this is our custom class */
.redHighlight {
background: red;
color: #fff;
}
JavaScript
(function($) {
$.fn.highlight = function( custom ) {
// Default settings
var settings = $.extend({
text : (typeof custom === "string") ? custom : "",
class : "highlight",
}, custom);
return this.each(function() {
var rgx = new RegExp('('+ settings.text +')', 'ig');
$(this).add("*", this).contents().filter(function() {
return this.nodeType === 3;
}).text(function(i, txt) {
$(this).replaceWith(txt.replace(rgx, '<span class="'+ settings.class +'">$1</span>'));
});
});
};
}( jQuery ));
// Passing string as only parameter
$("#one").highlight("gh"); // Highlight "gh" string
// Passing more options (Object Literal)
$("#two").highlight({
text: "gh",
class: "redHighlight" // Reference to a custom CSS class
});