Firing a click event on a button when the event is added to all buttons to reveal the clicked button text

Viewed 20

I added the click event to all buttons but my intention is to have the event occur on a button inorder to extract the buttons text(btnText).

I have tried the .removeClass() and .addClass() methods but its still not working as I expected.

<ul>
  <li><button>Dog</button></li>
  <li><button>Cat</button></li>
  <li><button>Moose</button></li>
</ul>
$('button').click(() => {
        $('button').removeClass("selected");
        $(this).addClass("selected");
        let btnText = $(this).text(); *// expected result(Dog|Cat|Moose)*
        console.log(btnText); *// printed result (DogCatMoose)*
}); // end click
1 Answers

That's because of the arrow function which makes this refer to the outer scope which this is window, you need to use function declaration instead to make this refers to the clicked button.

$('button').click(function () {
        $('button').removeClass("selected");
        $(this).addClass("selected");
        let btnText = $(this).text(); // expected result(Dog|Cat|Moose)*
        console.log(btnText); // printed result (DogCatMoose)*
}); // end click
.selected {
  background-color: red;
  color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li><button>Dog</button></li>
  <li><button>Cat</button></li>
  <li><button>Moose</button></li>
</ul>

Related