JSFiddle - React, Tailwind, and code Playground
HTML
<div id = "data" >Hi all. Hello world. Good morning. Good morning.<div/>
<input id="btn" type="submit" value="Highlight" />
CSS
#data {
font-size : 20px;
color : black;
}
.highlightedText {
background-color : red;
}
.replaceBgColor {
background-color: white;
}
JavaScript
$("#btn").click(function () {
var selectedText = window.getSelection ? window.getSelection() : document.selection.createRange(); // second one for IE
var textd = $("#data").html();
var normalText = $("#data").text();
if (selectedText.getRangeAt) {
var range = selectedText.getRangeAt(0);
var newNode = document.createElement("span");
newNode.setAttribute('class', 'highlightedText');
range.surroundContents(newNode);
} else {
selectedText.pasteHTML('<span class="highlightedText">' + selectedText.htmlText + '</span>');
}
$('.highlightedText').replaceWith(swapText);
});