Skip to content

Instantly share code, notes, and snippets.

@quephird
Last active February 16, 2017 23:51
Show Gist options
  • Save quephird/2fc953adca22210e5d19c6c810e4457b to your computer and use it in GitHub Desktop.
Save quephird/2fc953adca22210e5d19c6c810e4457b to your computer and use it in GitHub Desktop.
Just a silly experiment with `purescript-dom` to create a button and add it to the document body.
import Prelude
import Data.Maybe
import Data.Nullable
import DOM.HTML as h
import DOM.HTML.Document as hd
import DOM.HTML.Types as ht
import DOM.HTML.Window as w
import DOM.Node.Document as nd
import DOM.Node.Node as n
import DOM.Node.Types as nt
import Partial.Unsafe
addNewButton = do
globalWin <- h.window
htmlDoc <- w.document globalWin
let doc = ht.htmlDocumentToDocument htmlDoc
newButton <- nd.createElement "BUTTON" doc
let newButtonNode = nt.elementToNode newButton
docNode = nt.documentToNode doc
nullableBody <- hd.body htmlDoc
let actualBody = unsafePartial $ fromJust $ toMaybe nullableBody
bodyNode = nt.elementToNode $ ht.htmlElementToElement actualBody
newNode <- n.appendChild newButtonNode bodyNode
pure unit
@dmbfm
Copy link

dmbfm commented Feb 16, 2017

Thanks for this! I was going crazy trying to figure out how to unwrap the body from the Nullable type!

@dmbfm
Copy link

dmbfm commented Feb 16, 2017

I'm curious; do you know if there's anyway to do this without using unsafe partials?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment