0

There are lots of ways to empty out a element of a DOM node with JavaScript. I would like to do this with PureScript (with the intent of replacing static content with a Halogen widget). It seems like among all the functions of purescript-web-html and purescript-web-dom there ought to be an obvious way to to this, but the huge number of conflicting ways to describe a element are defeating me.

Is there a one or two line easy way to do what seems like an obvious operation before calling runUI?

John F. Miller
  • 26,961
  • 10
  • 71
  • 121

1 Answers1

0

I'm not sure if this is the best way to do this as it seems like there ought to be a nice functional way to map over an HTMLCollection, but at least it works:

import Data.Maybe (Maybe(..))
import Effect (Effect)
import Halogen.Aff as HA
import Halogen.VDom.Driver (runUI)
import Web.DOM.ParentNode
import Web.DOM.ChildNode (remove)
import Web.HTML.HTMLElement (HTMLElement, toParentNode)
import Web.DOM.Element (toChildNode)
import Effect.Class

selector :: QuerySelector
selector = QuerySelector "#halogen"

main :: Effect Unit
main = HA.runHalogenAff do
  body <- HA.awaitBody
  elem <- HA.selectElement selector
  case elem of
    Nothing -> runUI component unit body
    Just e -> do
       liftEffect $ clearChildren e
       runUI component unit e

clearChildren :: HTMLElement -> Effect Unit
clearChildren e = clearNextChild (toParentNode e)
  where
    clearNextChild :: ParentNode -> Effect Unit
    clearNextChild n = do
      last <- lastElementChild n
      case (last) of
        Nothing -> pure unit
        Just elem -> do 
          remove $ toChildNode elem
          clearNextChild n
John F. Miller
  • 26,961
  • 10
  • 71
  • 121