Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I add a class to an element if a matching class exists?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading