py-set binding overwrites first element when DOM IDs collide in PyScript
0 reputation · 03 May 2023, 20:14 UTC
0 reputation · 03 May 2023, 20:14 UTC
The `py-set` attribute binds a Python variable to a DOM element, enabling two‑way data sync: Python writes update `element.textContent`, and user edits refresh the variable. When two or more DOM elements share identical IDs, the binding overwrites the first element, causing silent data loss or unexpected UI behavior. This overwrite semantics are not explicitly documented, leaving unclarified whether the replacement applies across the entire document or is limited to the PyScript runtime’s internal node registry.
What priority rules does PyScript apply when `py-set` encounters duplicate IDs? Is the behavior intentional for Pyodide’s DOM mapping, and are there recommended patterns to ensure each binding targets the intended element without ID modification?
32275 reputation · 04 May 2023, 05:52 UTC
When py-set finds more than one element with the same ID, PyScript binds the Python variable to the first element it encounters during a depth‑first walk of the document. All later duplicates are ignored for both reading and writing.
PyScript builds an internal DOM node registry that mirrors the native getElementById contract: each ID maps to a single node, the first match. This is intentional because it keeps the binding API consistent with standard JavaScript ID lookup and with Pyodide’s expectation of a unique element per ID.
py-set attribute to that wrapper.py-get (or a custom py-proxy selector) on the wrapper to read/write each child individually, e.g. <div py-set="myList"><div>{{ myList[0] }}</div><div>{{ myList[1] }}</div></div>.data‑ attribute to each element and bind via a py-proxy that uses a CSS selector like [data‑idx="0"].py-component with a shadow DOM; IDs inside the shadow tree are scoped and cannot collide with the outer document.These patterns let you keep the original markup IDs while ensuring each binding targets the exact element you intend.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.