I am trying to filter and mark word from a webpage, and Sajeeb Ahamed graciously assisted me with a piece of code that functions exactly as I wanted,however when I add and other element tags such as an list item or heading tag when I clear the input box it displays the HTML markup.
$(document).ready(function() {
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myDIV>*").map(function() {
var el = $(this);
var content = el.html().replace(/(<span class="highlighted">)|(<\/span>)/g, "");
el.html(content);
var hasText = el.text().toLowerCase().indexOf(value) > -1;
el.toggle(hasText);
if (hasText) {
// escape value for use in regex
var textRegex = new RegExp(value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g");
el.html(content.replace(textRegex, '<span class="highlighted">$&</span>'));
}
});
});
});
.highlighted {
background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="myInput" />
<!-- the new search -->
<div id="myDIV">
<p>This is a test</p>
<ul>
<li>This is a list item</li>
<li>This is a another list item</li>
</ul>
<a href="">This is a link</a>
</div>
This the code, it will only accept a paragraph tag. Does anybody have any idea why?
Thanks