JSFiddle - React, Tailwind, and code Playground
by MadDev82
HTML
<html>
<head>
<script type = "text/javascript" src="script.js"></script>
</head>
<body>
<label for="lname">Search</label>
<input type="text" id="word" name="lname"><br><br>
<input type="submit" value="Submit" onclick="HighLightText();">
<p>
<div class="search-mark">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
</p>
</body>
</html>
JavaScript
function HighLightText() {
var contentElement = document.getElementById("content");
let word = document.getElementById("word").value;
let className = "search-mark";
let criterial = "Any position"; //Can be "Ends with" | "Starts with" | "Coincident".
let scrollDetail = false;
var searchResults = document.getElementsByClassName(className);
if (window.find && window.getSelection) {
document.designMode = "on";
var sel = window.getSelection();
sel.collapse(document.body, 0);
var listOfWord = [];
switch (criterial) {
case "Coincident":
listOfWord.push(" " + word + "");
listOfWord.push(word + " ");
// ...more cases where the word is found
break;
case "Any position":
listOfWord.push(word);
break;
case "Ends with":
listOfWord.push(word + ".");
listOfWord.push(word + ",");
listOfWord.push(word + "!");
listOfWord.push(word + "?");
// ...more cases where the word is found
break;
case "Starts with":
listOfWord.push(" " + word);
// ...more cases where the word is found
break;
}
listOfWord.forEach(singleWord => {
while (window.find(singleWord)) {
scroll(0, scrollDetail)
document.execCommand("insertHTML", false, '<b><mark>' + window.getSelection().toString() + '</mark></b>');
}
});
sel.collapseToEnd();
document.designMode = "off";
} else if (document.body.createTextRange) {
var textRange = document.body.createTextRange();
textRange.moveToElementText(contentElement);
while (textRange.findText(text)) {
textRange.execCommand("BackColor", false, "yellow");
...