Fix for #2467 with tests to ensure it works. (#2468)

This commit is contained in:
Nicholas Tollervey
2026-04-08 12:56:18 +01:00
committed by GitHub
parent 1c6be7e84a
commit 7f856a107e
3 changed files with 19 additions and 3 deletions

File diff suppressed because one or more lines are too long

View File

@@ -1112,7 +1112,10 @@ class ElementCollection:
return ElementCollection(self._elements[key])
if isinstance(key, str):
for element in self._elements:
result = _find_by_id(element._dom_element, key)
element_id = key[1:] if key.startswith("#") else key
if element.id == element_id:
return element
result = _find_by_id(element._dom_element, element_id)
if result:
return result
return None

View File

@@ -673,15 +673,28 @@ class TestCollection:
def test_collection_getitem_by_id(self):
"""Test looking up element by id in collection."""
div1 = web.div(web.p("Child", id="find-me"))
div2 = web.div(web.p("Child 2"))
div2 = web.div(web.p("Child 2"), id="other-div")
collection = web.ElementCollection([div1, div2])
web.page.body.append(div1)
web.page.body.append(div2)
# Find a child element by id.
result = collection["find-me"]
assert result is not None
assert result.id == "find-me"
# Find an element contained within the collection by id.
result = collection["other-div"]
assert result is not None
assert result.id == "other-div"
# Check with # prefix as well.
result = collection["#find-me"]
assert result is not None
assert result.id == "find-me"
# And for the other one too.
result = collection["#other-div"]
assert result is not None
assert result.id == "other-div"
class TestCreation: