The issue to solve is to inactivate the months that are not in the list. I have a list of posts that populates the DOM and an unordered list aside. I only want the user to see the months highlighted where there is a matching HTML row.
Here is what my html looks like:
<div data-filter="February">Feb</div>
<div data-filter="April">Apr</div>
Here is my unordered list:
<ul>
<li>January</li>
<li>February</li>
<li>March</li>
<li>April</li>
<li>May</li>
<li>June</li>
<li>July</li>
<li>August</li>
<li>September</li>
<li>October</li>
<li>November</li>
<li>December</li>
</ul>
Can someone please show me the logic to only highlight the months of February and April?
Thanks!
>Solution :
You can do the following:
- Use nested loops to iterate over the elements.
- Take the substring of the first 3 characters for list elements, and set
font-weight
property to bold if the substring matches the div text content.
Check following code:
const filterElements = document.querySelectorAll('[data-filter]');
const listElements = document.querySelectorAll('li');
listElements.forEach(function(listElement) {
filterElements.forEach(function(filterElement) {
var el = listElement.textContent.substring(0, 3);
if (el === filterElement.textContent) {
listElement.style.fontWeight = 'bold';
}
});
});
<ul>
<li>January</li>
<li>February</li>
<li>March</li>
<li>April</li>
<li>May</li>
<li>June</li>
<li>July</li>
<li>August</li>
<li>September</li>
<li>October</li>
<li>November</li>
<li>December</li>
</ul>
<div data-filter="February">Feb</div>
<div data-filter="April">Apr</div>