pjk_ok
pjk_ok

Reputation: 947

Add a CSS Class to an Element When A String Matches the Required Text - JavaScript

I've started to learn regular expressions in JavaScript. Although there are lots of tutorials about the matching characters etc I can't seem to work out how to make the HTML string something I can match?

I want to create an if statement so when the string matches what I want to match, I can add a CSS class to a nav menu item.

In the code below the console.log(termName[i].textContent) shows that the strings themselves, but how do I use a regex (or string method) to add the CSS class the menu item if the anchor has the .textContent of 'Marketing'?

CodePen: https://codepen.io/emilychews/pen/abOJMwa

Thanks,

Emily

var termName = document.querySelectorAll('.single-news-cat a'),
    menuItem = document.getElementsByClassName('menu-item-1') [0]
    

for (i = 0; i < termName.length; i+=1) {

      // shows strings in console
      console.log(termName[i].textContent)

      // pseudo code for matching 
      if (termName[i].textContent == 'Marketing') {
          menuItem.classList.add('active')
      }
        
}
body {
  margin: 0;
  display: flex;
  height: 100vh;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%
}

.single-news-cat {
  margin-top: 3rem;
}

.menu-item-1.active {
  color: red;
}
<div class="menu-item menu-item-1">Dev</div>

<div class="single-news-cat">
    <a href="#">Marketing</a>
    <a href="#">Design</a>
</div>

Upvotes: 0

Views: 694

Answers (2)

Jeppe Hasseriis
Jeppe Hasseriis

Reputation: 310

This should help you.

var termName = document.querySelectorAll('.single-news-cat a'),
    menuItem = document.querySelector('.menu-item-1');

for (i = 0; i < termName.length; i+=1) {

      // shows strings in consolue
      console.log(termName[i].textContent)

      // pseudo code for matching 
      if (/marketing/i.test(termName[i].textContent)) {
          menuItem.classList.add('active')
      }

}

This uses the regex test method with case insensitive.
Also changed getElementsByClassName to querySelector.

Upvotes: 0

boosted_duck
boosted_duck

Reputation: 498

Try using includes.

if (termName[i].textContent.includes('Marketing')) {
      menuItem.classList.add('active')
}

Upvotes: 1

Related Questions