-4

I want to color these elements using the same function. When I click on one of them, the same element that was clicked will be colored. How is that done using JavaScript

<button class="btn" onclick="color()">A</button>
<button class="btn"onclick="color()">B</button>
  • Inline event handlers like `onclick` are [not recommended](/q/11737873/4642212). They are an [obsolete, hard-to-maintain and unintuitive](/a/43459991/4642212) way of registering events. Always [use `addEventListener`](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#inline_event_handlers_%E2%80%94_dont_use_these) instead. – Sebastian Simon Mar 28 '21 at 02:59
  • Use [event delegation](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Event_delegation) instead of assigning multiple events — it’s more maintainable, and applies to dynamically added elements. E.g., use an [event argument](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#The_event_listener_callback)’s [`target`](https://developer.mozilla.org/en-US/docs/Web/API/Event/target). See [the tag info](/tags/event-delegation/info) and [What is DOM Event delegation?](/q/1687296/4642212). – Sebastian Simon Mar 28 '21 at 03:00
  • 1
    [Duplicate](https://google.com/search?q=site%3Astackoverflow.com+js+onclick+attribute+get+clicked+element) of [Get element from which onclick function is called](https://stackoverflow.com/q/40234130/4642212). – Sebastian Simon Mar 28 '21 at 03:04

1 Answers1

-2
const $button = document.querySelector('.btn')

$button.addEventListener('click', () => {
 $button.style.color = "#0099ff"
})
  • Why adding $ in variable name? It's not a jquery selection. Another issue in your code is that querySelector will only return first button. what you need to do instead is select all buttons `document.querySelectorAll` and then you for loop to add event listener on each button. – Denis Omerovic Mar 28 '21 at 09:01