Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

208
Views
Add a class to a span with a particular text

My initial problem is that I want to put custom colours on my main menu titles. I have done this by using the title + attribute in the CSS. However I don't want the title attribute to appear when hovered over. So I had another idea and wondered if it was possible to add a class (with JS) to a specific text? And if so how to do it?

Each menu title has the following structure: <span class="menu-text">Random text</span>

They all have the "menu-text" class and that's why I'm trying to differentiate them. In order to apply a different colour.

Thank you in advance for your answers!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

This illustrates a simple way to add a class to an element when it is clicked.

window.addEventListener("load", function(){
    // gets the elements with the classname .menu-text in a nodeList
    const getAllElements = document.querySelectorAll('.menu-text');
    
    for (let item of getAllElements) {
      // iterates over all of them, and attaches an event
      item.addEventListener('click', function () {
        // adds the class .has-background-red
        this.classList.add('has-background-red');
      });
    }
});
.container {
  /* just for visual purposes */
  display: flex;
  gap: 16px;
}

.has-background-red {
  background-color: red;
}
<div class="container">
  <span class="menu-text">Random text</span>
  <span class="menu-text">Random text</span>
  <span class="menu-text">Random text</span>
  <span class="menu-text">Random text</span>
  <span class="menu-text">Random text</span>
  <span class="menu-text">Random text</span>
  <span class="menu-text">Random text</span>
  <span class="menu-text">Random text</span>
  <span class="menu-text">Random text</span>
</div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!