On Thu, Mar 03, 2016 at 08:28:00AM -0800, Han-Wen Nienhuys wrote:
> Hi there,
>
> I'm toying with gopherjs. I was wondering if there is a suggested method to
> create DOM elements programmatically.
>
> [...]
>
> I could write out the HTML in the div element, and then have the browser
> parse it back, but I was wondering if I can create the nodes and insert
> them into the DOM directly.
With the plain DOM API and
honnef.co/go/js/dom, that would look
something like this (
http://www.gopherjs.org/playground/#/RZpM56qIBX):
> func main() {
> d := dom.GetWindow().Document().(dom.HTMLDocument)
> body := d.Body()
> elts := []string{"a", "bb"}
> for i, s := range elts {
> span := d.CreateElement("span")
> span.Class().Add("bla")
> span.SetID(strconv.Itoa(i))
> span.SetTextContent(s)
> body.AppendChild(span)
> }
> }
If your question was more general and not about
honnef.co/js/dom in
particular: There are a number of packages for building DOMs
programmatically. Some provide Go APIs, some parse HTML or rely on
html/template. Check out
https://github.com/gopherjs/vecty or
https://github.com/albrow/vdom, for example.
--
Dominik Honnef