Selecting Elements By Id in Purescript

932 views Asked by At

Is there a function in purescript-halogen to select an element by it's id, or do I need to custom role it (which would seem very strange to me).

I'm reading through the documentation on Pursuit, and I see a selectElement function in Util, but nowhere do I see something that lets me select by id.

I can use getElementById :: ElementId -> NonElementParentNode -> Eff () (Nullable Element) to get an Element, but I do not know how to turn this Element into an HTMLElement.

The type search feature in Pursuit is also lacking, so I apologize for this naive question.

1

There are 1 answers

0
gb. On BEST ANSWER

This isn't something you should generally do when working with libraries that use a virtual DOM, since if you save a reference to an element by id it can end up stale and referring to a totally different element, or an element that is no longer attached to the DOM.

The way to get hold of an element is to use ref, there is an example of using it in this section of the guide. It works something like an event handler, where a query is raised on the component whenever the element comes into existence or is removed. If you use a query that updates a reference in the component state you can be sure to know that you always have the actual element you want (or Nothing if it doesn't exist for some reason).

If you really want to use getElementById then it is available from purescript-dom. It's not part of Halogen, as Halogen is not for general purpose DOM manipulation. Those utility functions are only provided to make it easier to initialise a Halogen app.