HTML Element classList Property in Go
Manipulate CSS classes of an HTML element via classList property of the element. We can add, remove, or toggle the class of an element, or test if some class exists in the class attribute of the element via contains method. For the full list of methods provided in classList, see Element.classList - Web APIs | MDN.
Table of Content
Manipulate classList Property
Assume we have the following div element in our HTML:
<div id="foo">Hello World</div>
And also the following CSS class:
.invisible { display: none; }
We will show you how to add the invisible class to the div element via the classList property. For other manipulations like remove, toggle, or contains, the usage is similar and we will not cover here.
JavaScript
var f = document.querySelector("#foo");
f.classList.add("invisible");
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")
f.Get("classList").Call("add", "invisible")
}
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")
f.ClassList().Add("invisible")
}
The full code example of this post is on my GitHub.
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 |