1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-27 02:47:35 +00:00

LibWeb: Add capabilities to find the index of a child in its parent.

For Elements depending on the index they are inside their parent. Most
notably the <ol> element.
Also added a typed version to only count children of a certain type.

This patch is work towards #2059
This commit is contained in:
Tobias Christiansen 2021-04-17 23:05:56 +02:00 committed by Andreas Kling
parent e92bffb2e3
commit c09ac536c5

View file

@ -97,6 +97,39 @@ public:
return const_cast<TreeNode*>(this)->child_at_index(index); return const_cast<TreeNode*>(this)->child_at_index(index);
} }
Optional<size_t> index_of_child(const T& search_child)
{
VERIFY(search_child.parent() == this);
size_t index = 0;
auto* child = first_child();
VERIFY(child);
do {
if (child == &search_child)
return index;
index++;
} while (child && (child = child->next_sibling()));
return {};
}
template<typename ChildType>
Optional<size_t> index_of_child(const T& search_child)
{
VERIFY(search_child.parent() == this);
size_t index = 0;
auto* child = first_child();
VERIFY(child);
do {
if (!is<ChildType>(child))
continue;
if (child == &search_child)
return index;
index++;
} while (child && (child = child->next_sibling()));
return {};
}
bool is_ancestor_of(const TreeNode&) const; bool is_ancestor_of(const TreeNode&) const;
bool is_inclusive_ancestor_of(const TreeNode&) const; bool is_inclusive_ancestor_of(const TreeNode&) const;
bool is_descendant_of(const TreeNode&) const; bool is_descendant_of(const TreeNode&) const;