I built a loop to iterate and create event listeners for a given class name. The hobby project is to create a simple calculator. My logic will be using data-...
attributes of the buttons in various functions. There are total of 24 buttons in the calculator.
My JS is at a roadblock because the event.target
isn't returning consistent objects, so I cannot rely on when the target
will be the correct object.
Here is en example of one html button:
<button data-type="input" data-value="7" data-ignore-history="0" data-history-symbol="7" class="calcButton">
<i class="fa-solid fa-7"></i>
</button>
Here is my object query:
const calcButtons = document.getElementsByClassName("calcButton");
Here is my event listener:
for (let i = 0; i < calcButtons.length; i++) {
calcButtons[i].addEventListener('click', (event) => {
console.log(event);
console.log(event.target);
console.log(event.target.offsetParent);
console.log(event.target.offsetParent.dataset); // need consistent access to data attributes of button
});
}
Problem is that it doesn't return consistently. Sometimes the event.target
is the button, most often it is the <i>'fontawesome'</i>
tag. I initially expected the <button>
tag to be the target
, but my initial tests in the console returned the <i>
, which is why I was using the .offsetParent
to access the button attributes.
Further, if the issue is occurring on a certain button, it can correct after clicking on other buttons sometimes.