Lets say I have a sorting list like this
.dropbtn {
background-color: #04AA6D;
color: white;
padding: 16px;
font-size: 16px;
border: none;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-content a:hover {
background-color: #ddd;
}
.dropdown:hover .dropdown-content {
display: block;
}
.dropdown:hover .dropbtn {
background-color: #3e8e41;
}
<div class="dropdown">
<button class="dropSortbtn2"> Food <i class="bi bi-caret-down"></i></button>
<div class="dropdown-content">
<a href="#">Tomato</a>
<a href="#">APPle</a>
<a href="#">Carrot</a>
<a href="#">Broccoli</a>
</div>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
I want that drop down list to sort list of items and hide others,
so for example if I have this list
<ul>
<li>Tomato</li>
<li>APPle</li>
<li>Broccoli</li>
<li>Carrot</li>
<li>Tomato</li>
<li>Broccoli</li>
</ul>
And the user click tomato in the drop down list, all items should be hidden and only tomato elements will be shown. What is the correct way to do this ? knowing that the sorting drop down list will be really long.
CodePudding user response:
You can add a click
event listener to all select options that loops through each li
in the ul
and hides those whose textContent
is not equal to the textContent
of the select option clicked.
const options = document.querySelectorAll('.dropdown .dropdown-content a')
const listItems = document.querySelectorAll('#list li');
options.forEach(f => f.addEventListener('click', function(e){
let text = this.textContent;
listItems.forEach(e => e.style.display = e.textContent == text ? "block" : "none")
}))
.dropbtn {
background-color: #04AA6D;
color: white;
padding: 16px;
font-size: 16px;
border: none;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-content a:hover {
background-color: #ddd;
}
.dropdown:hover .dropdown-content {
display: block;
}
.dropdown:hover .dropbtn {
background-color: #3e8e41;
}
<div class="dropdown">
<button class="dropSortbtn2"> Food <i class="bi bi-caret-down"></i></button>
<div class="dropdown-content">
<a href="#">Tomato</a>
<a href="#">APPle</a>
<a href="#">Carrot</a>
<a href="#">Broccoli</a>
</div>
</div>
<ul id="list">
<li>Tomato</li>
<li>APPle</li>
<li>Broccoli</li>
<li>Carrot</li>
<li>Tomato</li>
<li>Broccoli</li>
</ul>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>