In the sample code below , on large blocks of text I am getting copious amounts of white space (blank lines) after filtering the text.
The issue predominantly manifests with the <span>
-tags, but in my actual code (JQuery targeting an iframe) I am getting the same issue with <p>
or li
elements tagged with the .vis
class.
In the example below,
- the first few items display correctly (just the matched lines displayed; no extra white space);
- later items filtered / selected (exemplified by the
<span>
-tagged text) are pushed down, below white space.
For example, type lemon
or mango
("ok"), and compare to soup
or tea
(extra white space).
- JSFiddle here: https://jsfiddle.net/vstuart/fqw0p4dg/1/
$('#snippets_search_box').keyup(function() {
const valThis = this.value;
const length = this.value.length;
$('.vis').each(function() {
const text = $(this).text().replace(/<span class=\"vis\">/gi, "").replace(/<\/span>/gi, "");
const position = text.indexOf(valThis.toLowerCase());
if (position !== -1) {
const matches = text.substring(position, (valThis.length + position));
const regex = new RegExp(matches, 'ig');
const highlighted = text.replace(regex, `<mark>${matches}</mark>`);
$(this).html(highlighted).show();
} else {
$(this).text();
$(this).hide();
}
});
});
input {
width: 50%;
margin: 10px;
padding: 5px;
float: left;
clear: left;
}
div {
float: left;
clear: left;
//margin: 10px 10px;
}
p.vis {
clear: left;
margin: 0.0rem 0.0rem 0.0rem 0.0rem;
}
span.vis {
clear: left;
color: brown;
margin: 0.0rem 0.0rem 1.0rem 0.0rem;
}
.bold {
font-weight: 700;
}
table td {
border: solid 1px #ccc;
padding: 3px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!--
BASED ON:
* https://stackoverflow.com/questions/59178447/search-and-highlight-text-on-page-while-keeping-html-structure
* https://jsfiddle.net/SchweizerSchoggi/6x3ak5d0/7/
-->
<head>
<input placeholder="Filter these results" id="snippets_search_box" type="text" />
</head>
<body>
<div>
<p class="vis">apples</p>
<p class="vis">bananas</p>
<p class="vis">cakes</p>
<p class="vis">donuts</p>
<li class="vis">eggs</li>
<li class="vis">fish</li>
<li class="vis">grapes</li>
<li class="vis">ham</li>
<li class="vis">ice cream</li>
<li class="vis">jello</li>
<li class="vis">kefir</li>
<li class="vis">lemon</li>
<span class="vis">mango</span><br />
<span class="vis">nachos</span><br />
<span class="vis">oranges</span><br />
<span class="vis">peaches</span><br />
<span class="vis">quiche</span><br />
<span class="vis">radishes</span><br />
<span class="vis">soup</span><br />
<span class="vis">tea</span><br />
</div>
</body>
` after the element – epascarello Sep 21 '22 at 00:19
` element. Per https://stackoverflow.com/a/59368164/1904943 I replaced it with