он должен переключать ребенка, когда я нажимает соответствующий родительский список результатов поиска. />
document.addEventListener('DOMContentLoaded', function() {
const searchBox = document.getElementById('menuSearch');
// Toggle dropdowns manually
document.querySelectorAll('.shopMenuList li.has-children > span').forEach(toggle => {
toggle.addEventListener('click', function() {
const parentLi = this.parentElement;
parentLi.classList.toggle('open');
});
});
// Recursive filter function with toggleable matched items
function filterListItems(element, searchTerm) {
let matchFound = false;
// Check direct children [*]
const children = Array.from(element.children);
children.forEach(child => {
if (child.tagName === 'UL') {
const grandChildren = Array.from(child.children);
grandChildren.forEach(grandChild => {
const matched = filterListItems(grandChild, searchTerm);
matchFound = matchFound || matched;
});
}
});
const text = element.textContent.toLowerCase();
const isMatch = text.includes(searchTerm);
const shouldShow = isMatch || matchFound;
element.style.display = shouldShow ? '' : 'none';
element.classList.toggle('open', matchFound); // auto-expand matching
return shouldShow;
}
// Search input handler
searchBox.addEventListener('input', function() {
const filter = this.value.trim().toLowerCase();
const allRootItems = document.querySelectorAll('.shopMenuList > li');
allRootItems.forEach(item => {
filterListItems(item, filter);
});
// Toggle visibility of children if any match
document.querySelectorAll('.shopMenuList li.has-children').forEach(li => {
const hasVisibleChild = li.querySelector('ul > li:not([style*="display: none"])');
if (hasVisibleChild) {
li.classList.add('open');
} else {
li.classList.remove('open');
}
});
// Collapse all if search is empty
if (filter === '') {
document.querySelectorAll('.shopMenuList li.has-children').forEach(li => {
li.classList.remove('open');
});
}
});
});< /code>
/*class that gets added to toggle lists when clicked*/
.open{
border: solid 1px;
background: dodgerblue;
}< /code>
- Ceramic Tiles
Floor Tiles
15x80
Matte
- Matte
- Matte
- Matte
- Matte
- Matte
- Glossy
- Rough
- Glossy
- Matte
- Rough
- Glossy
- Matte
- Rough
< /code>
< /div>
< /div>
< /p>
При поиске списка родителей он отобразит только соответствующий родительский список, а родитель этого родителя, который является правильным ... а затем, когда я нажимает на соответствующий родительский список, он не будет переключать детей.ceramic tiles
floor tiles
30x40 - (searched list)
matte - (it doesnt display when the search list is toggled)
< /code>
Правильный путь < /p>
ceramic tiles
floor tiles
30x40 - (searched list) then (clicked to toggle the child)
matte - (it should display)
Подробнее здесь: https://stackoverflow.com/questions/797 ... -searching
Мобильная версия