Javascript not working using Go

If I use jsfiddle this works as it should:

const btns = document.querySelectorAll(".btn");
const nav = document.querySelector(".nav");

https://jsfiddle.net/0x54fL7t/10/

Using Javascript in Go it does querySelectorAll() work…
image
But not querySelector

image
Why does exact the same code work outside Go, but not using Go?

Any tip what I am doing wrong?

What do you mean by that? How do you execute JavaScript “using Go”?

In main:

func init() {
tpl = template.Must(template.ParseGlob("public/templates/*.html"))
http.Handle("/js/", http.StripPrefix("/js/", http.FileServer(http.Dir("./public/js"))))
}

In httphead:

<head>
    <script type="text/javascript" src="/js/nav.js"></script >
</head>

In main template:

  <div class="nav">
      {{template "nav" ("faq")}}
  </div>

In nav.js

const btns = document.querySelectorAll(".btn");
const nav = document.querySelector(".nav");

alert(nav)
alert(btns)

So the Javascript is called by the head inside a template.

The strange thing is at that:

document.querySelectorAll(".btn") ...works
document.querySelector(".nav"); ...fails

The only difference is that .btn is in a sub template. Both works outside Go.

I found the cause.

<head> 
   <script src="/js/nav.js" defer></script > 
</head>

It turned out that the Javascript was loaded before the page was loded. By adding defer it worked.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.