I have a list of vehicle models and would like to display the associated types. As a selector I have written the types in a data-field. Now I want to hide with the class d-none all list items that do not match the selection.
This works with my current code. The problem is that I also get "Example Type 3" displayed in this example. But I only want to have "Example Type 2".
How can I make it so that only the 2nd element is displayed here but I can still search for "E-Tron S" or "E-Tron GT"?
My javascript so far:
let searchText = "E-Tron";
containerItems = contentContainer.querySelectorAll('li[data-custom-field-filter-name^="Typ"]:not([data-custom-field-model*="' + searchText + '"])');
containerItems.forEach(function (el) {
el.classList.add('d-none');
});
html list
<ul class="container">
<li class="has-button" data-custom-field-filter-name="Typ" data-custom-field-model=" Q5">
<a href="#"><button> Example Type 1 </button></a>
</li>
<li class="has-button" data-custom-field-filter-name="Typ" data-custom-field-model=" E-Tron">
<a href="#"><button> Example Type 2 </button></a>
</li>
<li class="has-button" data-custom-field-filter-name="Typ" data-custom-field-model=" E-Tron S| E-Tron GT">
<a href="#"><button> Example Type 3 </button></a>
</li>
</ul>
There is no exact text matching or reg exp in the selector, so you need to do the filtering without using the contains selector.
const searchText = "E-Tron";
const allLis = document.querySelectorAll('li[data-custom-field-filter-name="Typ"]');
var regex = new RegExp("\\b" + searchText + "($|\\|)");
allLis.forEach(x => {
if(!regex.test(x.dataset.customFieldModel)) {
x.classList.add("d-none");
}
});
.d-none {
display: none;
}
<ul class="container">
<li class="has-button" data-custom-field-filter-name="Typ" data-custom-field-model=" Q5">
<a href="#"><button> Example Type 1 </button></a>
</li>
<li class="has-button" data-custom-field-filter-name="Typ" data-custom-field-model=" E-Tron">
<a href="#"><button> Example Type 2 </button></a>
</li>
<li class="has-button" data-custom-field-filter-name="Typ" data-custom-field-model=" E-Tron S| E-Tron GT">
<a href="#"><button> Example Type 3 </button></a>
</li>
</ul>