danneu/html-parser/1.0.0

NOTE: the latest version is 2.0.3

Html.Parser

Leniently parse html5 documents and fragments and then render them into strings or Elm's virtual dom nodes.

Definition

type Node
= Text String
| Comment String
| Element String (List ( String, String )) (List Node)

An html node is tree of text, comments, and element nodes.

An element (e.g. <div foo="bar">hello</div>) can have attributes and child nodes.

type alias Document =
{ legacyCompat : Bool
, root : Node
}

An html document has a <!doctype> and then a root html node.

Parse

run : String -> Result (List DeadEnd) (List Node)

Parse an html fragment into a list of html nodes.

The html fragment can have multiple top-level nodes.

run "<div>hi</div><div>bye</div>"
    == Ok
        [ Element "div" [] [ Text "hi" ]
        , Element "div" [] [ Text "bye" ]
        ]
runElement : String -> Result (List DeadEnd) Node

Like run except it only succeeds when the html input is a single top-level element, and it always returns a single node.

runDocument : String -> Result (List DeadEnd) Document

Parses <!doctype html> and any html nodes after.

Always returns a single root node. Wraps nodes in a root <html> node if one is not present.

Caveat: If there are multiple top-level nodes and one of them is <html>, then this function will wrap them all in another <html> node.

Render

nodeToHtml : Node -> Html msg

Turn a single node into an Elm html node that Elm can render.

nodesToHtml : List Node -> List (Html msg)

Turn a multiple html nodes into Elm html that Elm can render.

view : Html Msg
view =
    Html.div
        []
        ("<p>hello world</p>"
            |> Html.Parser.run
            |> Result.map Html.Parser.nodesToHtml
            |> Result.withDefault [ Html.text "parse error" ]
        )
nodeToString : Node -> String

Convert an html node into a non-pretty string.

nodeToString (Element "a" [] [ Text "hi" ])
    == "<a>hi</a>"
nodesToString : List Node -> String

Convert multiple html nodes into a non-pretty string.

nodesToString
    [ Element "a" [] [ Text "hi" ]
    , Element "div" [] [ Element "span" [] [] ]
    ]
    == "<a>hi</a><div><span></span></div>"

Generate a pretty string for a single html node.

nodesToPrettyString : List Node -> String

Turn a node tree into a pretty-printed, indented html string.

("<a><b><c>hello</c></b></a>"
    |> Html.Parser.run
    |> Result.map nodesToPrettyString
)
    == Ok """<a>
    <b>
        <c>
            hello
        </c>
    </b>
</a>"""
documentToString : Document -> String

Convert a document into a string starting with <!doctype html> followed by the root html node.

documentToPrettyString : Document -> String

Convert a document into a pretty, indented string.