Today I have a requirement, I hope that the block containing the keyword can be displayed when searching for the keyword in the input box! Instead of just turning keywords into red. Current progress: But currently I can only turn keywords into red. Difficulty encountered: How to make the snippets without keywords disappear, and only the content containing keywords appears. I have encountered difficulties here and tried for more than 3 hours, but I still don’t know how to achieve it. Hope to get your help, thank you. The image below is what I would expect to see after searching for keywords.
$(function() {
$("#js-search").on('click', function() {
let keyword = $("#keyWord").val()
$("p").each(function(index, el) {
if (el.innerText.includes(keyword)) {
el.innerText = el.innerText.replace(keyword, `<span class="red">${keyword}</span>`)
}
$(this).html(el.innerText);
});
});
});
.red {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="keyWord" type="text"><button id="js-search">search</button>
<ul>
<li>
<h1>about giving back</h1>
<p>This is the content of the answer about giving back</p>
</li>
<li>
<h1>Credit Card Payment Issues</h1>
<p>Credit card payment question content</p>
</li>
<li>
<h1>return the goods</h1>
<p>Content related to return issues</p>
</li>
<li>
<h1>register</h1>
<p>How to register as a member</p>
</li>
</ul>
3
Answers
It’s fairly simple. You just need to hide the parents of the elements NOT matching your keyword.
Like this:
This will solve your problem,its hide the parent element if its not contains the word that you searching for, otherwise it will be shown
You have to hide and show parents :