HTML Element style Property in Go


We can change how a HTML element is displayed by setting the inline style of the element. This post will show you how to set as well as get the style property of a HTML element. The full code example of this post is on my GitHub.

Inline Style Attribute

Assume we have the following div element in our HTML:

<div id="foo">Hello World</div>

We will show you how to set and get the inline style attribute of the div element. In the example, we will set the color of the element as red. For full list of CSS properties accessible via style, see CSS Properties Reference on MDN.

JavaScript

var f = document.querySelector("#foo");

// set the color of element
f.style.color = "red";

// get the color of element
console.log(f.style.color);

GopherJS

The above code in Go/GopherJS is as follows:

import (
      "github.com/gopherjs/gopherjs/js"
)

func main() {
      f := js.Global.Get("document").Call("querySelector", "#foo")

      // set the color of element
      f.Get("style").Set("color", "red")

      // get the color of element
      println(f.Get("style").Get("color").String())
}

GopherJS + godom

To make your code more readable, we can prettify the above code with godom:

import (
      . "github.com/siongui/godom"
)

func main() {
      f := Document.QuerySelector("#foo")

      // set the color of element
      f.Style().SetColor("red")

      // get the color of element
      println(f.Style().Color())
}

References:

[1][Golang] GopherJS DOM Example - Hide Element by display:none
[2][GopherJS] Set/Get DOM CSS
[3][GopherJS] Insert CSS Dynamically
[4][GopherJS] Test if an Element Contains a Class
[5][GopherJS] Animate.css Test Demo
[6][Golang] GopherJS Synonyms with JavaScript