Creating new DOM nodes in DOM package?

78 views
Skip to first unread message

Han-Wen Nienhuys

unread,
Mar 3, 2016, 11:28:00 AM3/3/16
to GopherJS
Hi there,

I'm toying with gopherjs. I was wondering if there is a suggested method to create DOM elements programmatically.  For example, if my Go program has a list of strings

  elts :=  []string{"a", "bb"}

what would I do to transform those to

<div id="container">
  <span class="bla" id="1">a</span>
  <span class="bla" id="1">bb</span>
</div>

?

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.

Dominik Honnef

unread,
Mar 3, 2016, 12:30:17 PM3/3/16
to GopherJS
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
Reply all
Reply to author
Forward
0 new messages