[Clojurescript] .getElementById returns NULL

1,526 views
Skip to first unread message

Nathan Smutz

unread,
Jan 3, 2016, 9:04:24 PM1/3/16
to Clojure
Sorry if this is something trivial.  I tried to do some due diligence googling with no luck.
The function getElementById seems to be returning null where it shouldn't.

I'm currently using
lein-cljsbuild 1.1.2 
clojure 1.7.0
clojurescript 1.7.170
and compiling with optimizations: :none

Here's my HTML:
    <!DOCTYPE html>
    <html>
      <head>    
        <script src="js/main.js"></script>
      </head>
      <body>   
        <div id="test-content">Test text</div>
      </body>
    </html>

Here's my Clojurescript:
    (ns gol-cljs.core)
    (.log js/console (. js/document getElementById "test-content"))

This prints "null" to Chrome's browser console.
Attempting any operations on (. js/document getElementById "test-content")) gives errors about trying to do things with "null".

Is there some requirement I'm missing for accessing the dom?

Best,
Nathan


Ryan Fowler

unread,
Jan 3, 2016, 9:53:09 PM1/3/16
to clo...@googlegroups.com
On Sun, Jan 3, 2016 at 8:04 PM, Nathan Smutz <nsm...@gmail.com> wrote:

    (.log js/console (. js/document getElementById "test-content"))


​I suspect you need something more like this: ​
 (.log js/console (.getElementById js/document "test-content"))

Francis Avila

unread,
Jan 3, 2016, 10:49:39 PM1/3/16
to Clojure
Your problem is unrelated to clojurescript.

Your script runs before the body is loaded, so the test-content element doesn't exist yet.

Either load your script at the end of the body, or wrap your code in a document.onload event handler.

Nathan Smutz

unread,
Jan 6, 2016, 2:19:03 AM1/6/16
to Clojure
Thanks Francis, that did it.

Rookie mistake, that.
I wonder if there's ever enough page content to make it worth just delaying the DOM hooks.   
Reply all
Reply to author
Forward
0 new messages