Jquery - Change colour when click

Viewed 77

When I click I put the highligh but I want when I click again the highligh disappear or one button when I click he remove the last highlight.

$('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>

How I put the feature when I click again in the word he remove the highlight?

Thank you for help.

1 Answers

You could create a class and toggle it using 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>

Related