Is there an Document.getElementById() in Anvil.js?

What I’m trying to do:
Hey Guys, i am just redoing my work, cuz i do not like the way it behaves with Anvil Components. So i just did a simple HTML Page and all that stuff.
My question right know, is there a way to do something like
let el = document.getElementById(‘coolID’)?

Clone link:
https://anvil.works/build#clone:IXAFNMOLABW6NMGM=ZJOZETTQOG3L7LG2VTF2IQTO

sure - have you tried

from anvil.js.window import document

class Form1(Form1Template):
  def __init__(self, **properties):
    self.init_components(**properties)

  def form_show(self, **event_args):
    """This method is called when the HTML panel is shown on the screen"""
    print(document.getElementById('test'))

The only caveat is that accessing the document won’t work until form_show event fires since the html hasn’t loaded earlier than that.

Make sure you create the form_show event in the designer.
Screenshot 2021-08-19 at 07.16.05

Edit: You can also do something like

import anvil.js

class Form1(Form1Template):
  def __init__(self, **properties):
    self.init_components(**properties)
    self.dom_node = anvil.js.get_dom_node(self)
    print(self.dom_node.querySelector('#test'))
    # In this version we don't need to wait for the form_show
    # since the html is attached to the dom node for self 
    # (it's just not on the screen yet so not in the document)
4 Likes