Add an ID to the DOM node of all components

Add the following code to a client module, say utils.py.

from anvil.js import window, get_dom_node

def set_id(component, id):
  get_dom_node(component).setAttribute("id", id)

def set_component_ids(form):
  module = form.__class__.__module__.lower()
  for attr_name in dir(form):
    potential_component = getattr(form, attr_name)
    try:
      set_id(potential_component, f"{module}.{attr_name}")
    except TypeError:
      pass

Then you can import set_component_ids into all of your forms and use it in the form’s __init__:

from .utils import set_component_ids

class form_1(form_1Template):
  def __init__(self, **properties):
    self.init_components(**properties)
    set_component_ids(self)

Then boom, your DOM nodes have unique IDs :sunglasses:. The IDs have the following structure: <app_name>.<dir>.<component_name>, where <dir> is the location of your component, including any packages or parent forms that your component’s form might be nested in.

I used ideas from this topic so thanks and proper dues to Owen and Meredydd :slight_smile:

7 Likes