I need to remove all buttons except the one which was clicked (perhaps using e.target.id?) – according to its index (using for
loop.
I tried to create variable and declared it let buttonsX = buttons[i]
so I could refer to it later in the if
statement as !buttonsX
and then it would call all the array buttons EXCEPT the button with the current index (triggered by a mousedown
event).
But nothing happened.
I read there are the pull()
& splice()
functions but they would just require unnecessary lines of code that could’ve been prevented by a smaller code.
Other than them – I haven’t found any resources about such a function on the internet.
Also, it must be pure javascript,
Thank you very much.
3
Answers
You can simply use
.filter()
and check for the elements being different from the one you are not interested in:To complete this task in pure JS, you can use the forEach method to loop through all buttons and remove the ones that are not the clicked one. You can use the e.target to get the button that was clicked and then compare it to each button in the loop.
Hope this will help.
One way to achieve the desired behaviour would be to register an event handler on an element wrapping the buttons. When the event is triggered, check if a button is clicked. If the user didn’t click a button, exit early. If the user did click a button, loop through all the buttons within the container and remove them, except if the button matches the clicked button.
The above is optional in the current snippet and could be replaced by:
However if you plan to nest other elements within the button, like
<img>
,<span>
. The simplified version no longer works, sinceevent.target
is set to the deepest element clicked. So if I click "text" in<button><span>text</span></button>
thenevent.target
will be the<span>
element, not the button.Note that
this
in the event handler is the element that the event is attached to. In this case the button container<div>
, it’s the same asevent.currentTarget
.