Find all elements with a certain relative position to an HTML element.
elem_ancestors()
selects every element which contains the current element
(children, grand-children, etc.).
elem_parent()
selects the element that contains the current element.
elem_siblings()
selects every element which has the same parent as the
current element.
elem_children()
selects every element which is connected to and directly
below the current element.
elem_descendants()
selects every element that is contained by the current
element. The current element does not have to be a direct parent, but must
be some type of ancestor.
Value
All functions return a selenider_elements
object, except
elem_parent()
, which returns a selenider_element
object (since an
element can only have one parent).
Details
All functions except elem_children()
and elem_descendants()
use XPath
selectors, so may be slow, especially when using chromote
as a backend.
See also
http://web.simmons.edu/~grovesd/comm244/notes/week4/document-tree for a simple and visual explanation of the document tree.
find_element()
andfind_elements()
for other ways of selecting elements. These functions allow you to select ancestors using one or more conditions (e.g. CSS selectors).elem_filter()
andelem_find()
for filtering element collections.
Examples
html <- "
<html>
<body>
<div>
<div id='current'>
<p></p>
<div>
<p></p>
<br>
</div>
</div>
<div></div>
<p></p>
</div>
</body>
</html>
"
session <- minimal_selenider_session(html)
current <- s("#current")
# Get all the names of an element collection
elem_names <- function(x) {
x |>
as.list() |>
vapply(elem_name, FUN.VALUE = character(1))
}
current |>
elem_ancestors() |>
elem_expect(has_length(3)) |>
elem_names() # html, div, body
current |>
elem_parent() |>
elem_name() # div
current |>
elem_siblings() |>
elem_expect(has_length(2)) |>
elem_names() # div, p
current |>
elem_children() |>
elem_expect(has_length(2)) |>
elem_names() # p, div
current |>
elem_descendants() |>
elem_expect(has_length(4)) |>
elem_names() # p, div, p, br