I'm creating a glossary with a text field. When a user types in this text field, I want matches to appear. However, I only want elements classified as a title to be searched - I don't want the entire parent element searched.
For example:
function myFunction() {
var input, filter, cards, cardContainer, h5, title, i;
input = document.getElementById("glossaryFilter");
filter = input.value.toUpperCase();
cardContainer = document.getElementById("glossary-container");
cards = cardContainer.getElementsByClassName("glossary-item");
for (i = 0; i < cards.length; i++) {
title = cards[i].querySelector(".glossary-body h5.glossary-title");
if (title.innerText.toUpperCase().indexOf(filter) > -1) {
cards[i].style.display = "";
} else {
cards[i].style.display = "none";
}
}
}
<input type="text" id="glossaryFilter" onkeyup="myFunction()" placeholder="Search..">
<div id="glossary-container">
<div class="glossary-item">
<div class="glossary-body">
<h5 class="glossary-title">Title</h5>
<p>Content</p>
</div>
</div>
<div class="glossary-item">
<div class="glossary-body">
<h5 class="glossary-title">Title</h5>
<p>Content</p>
</div>
</div>
</div>
For the life of me I can't understand why this script isn't working... does anyone have any clues?
Read more here: https://stackoverflow.com/questions/66323904/filtering-by-child-element
Content Attribution
This content was originally published by DD1229 at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.