Can we delete an element with JS.dispatch?

Hi my friends, I can create phx-hook and delete the element I want, but I have a question, is there any JS module function in Phoenix LiveView to delete an element by ID?

for example something like this, (I know it does not work)

<button id="test" phx-click={JS.dispatch("click", to: "document.getElementById('test').remove()")}>
Click me!

Thank you in advance.

I don’t think you can do it directly on the element, but you can dispatch an event that triggers a callback on an event listener. See here Phoenix.LiveView.JS — Phoenix LiveView v0.17.9

1 Like

Yeah, with phx-hook I can be able to do this, I hope they prepare element remover as a JS module function

I wonder if it makes sense to add it. Your heex templates are a representation the structure of what’s rendered. If you start splitting concerns between js fragments and heex conditionals I can see that getting confusing.

Maybe you can dispatch a hide call, and push an event to change the state that would lead to that element being deleted. That way the server state would be the source of truth, while not waiting for a round trip to remove the element for the user.


For now, I am using phx-hook and JS.hide, I was just curious is there.a way not to write hook or not, that you say no.
Thank you