Fix a bug in <label> handling where 'for_' attribute should be 'htmlFor' on underlying HTML element. (#2352)

* Fix bug in label handling where 'for_' attribute should be 'htmlFor' on underlying HTML element.

* Fix comment.
This commit is contained in:
Nicholas Tollervey
2025-06-18 15:01:33 +01:00
committed by GitHub
parent 14cc05fb80
commit d68260c0c7
3 changed files with 22 additions and 2 deletions

File diff suppressed because one or more lines are too long

View File

@@ -124,6 +124,11 @@ class Element:
# Element instance via `for_`).
if name.endswith("_"):
name = name[:-1] # noqa: FURB188 No str.removesuffix() in MicroPython.
if name == "for":
# The `for` attribute is a special case as it is a keyword in both
# Python and JavaScript.
# We need to get it from the underlying DOM element as `htmlFor`.
name = "htmlFor"
return getattr(self._dom_element, name)
def __setattr__(self, name, value):
@@ -142,6 +147,11 @@ class Element:
# Element instance via `for_`).
if name.endswith("_"):
name = name[:-1] # noqa: FURB188 No str.removesuffix() in MicroPython.
if name == "for":
# The `for` attribute is a special case as it is a keyword in both
# Python and JavaScript.
# We need to set it on the underlying DOM element as `htmlFor`.
name = "htmlFor"
if name.startswith("on_"):
# Ensure on-events are cached in the _on_events dict if the

View File

@@ -871,7 +871,17 @@ class TestElements:
self._create_el_and_basic_asserts("kbd", "some text")
def test_label(self):
self._create_el_and_basic_asserts("label", "some text")
label_text = "Luke, I am your father"
label_for = "some-id"
# Let's create the element
el = web.label(label_text, for_=label_for)
# Let's check the element was configured correctly.
assert isinstance(el, web.label), "The new element should be a label."
assert el.textContent == label_text, "The label text should match."
assert el._dom_element.tagName == "LABEL"
assert el.for_ == label_for, "The label should have the correct for attribute."
# Ensure the label element is rendered with the correct "for" attribute
assert f'for="{label_for}"' in el.outerHTML, "The label should have the correct 'for' attribute in its HTML."
def test_legend(self):
self._create_el_and_basic_asserts("legend", "some text")