Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

203
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda