Jquery - Mudar a cor ao clicar [duplicar]

Sep 16 2020

Quando clico coloco o realce mas quero quando clico novamente o realce desaparece ou um botão quando clico remove o último realce.

$('div').each(function() { var $this = $(this); $this.html($this.text().replace(/\b(\w+)\b/g, "<span>$1</span>"));
});

$('div span').click(function() { $(this).css('background-color', '#ffff66');
});
span {
  font-size: 15pt;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" crossorigin="anonymous"></script>
<div>
  <span>This text is a test text</span>
</div>

Como coloco o recurso quando clico novamente na palavra ele remove o destaque?

Obrigado pela ajuda.

Respostas

3 IslamElshobokshy Sep 16 2020 at 17:48

Você pode criar uma classe e alterná-la usando toggleClass.

$('div').each(function() { var $this = $(this); $this.html($this.text().replace(/\b(\w+)\b/g, "<span>$1</span>"));
});

$('div span').click(function() { $(this).toggleClass('highlightSpan');
});
span {
  font-size: 15pt;
}

.highlightSpan {
  background-color: #ffff66;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" crossorigin="anonymous"></script>
<div>
  <span>This text is a test text</span>
</div>