1#' Get element name
2#'
3#' @param x A document (from [read_html()]), node set (from [html_elements()]),
4#'   node (from [html_element()]), or session (from [session()]).
5#' @return A character vector the same length as `x`
6#' @export
7#' @examples
8#' url <- "https://rvest.tidyverse.org/articles/starwars.html"
9#' html <- read_html(url)
10#'
11#' html %>%
12#'   html_element("div") %>%
13#'   html_children() %>%
14#'   html_name()
15#' @export
16#' @importFrom xml2 xml_name
17html_name <- function(x) {
18  xml_name(x)
19}
20
21#' Get element attributes
22#'
23#' `html_attr()` gets a single attribute; `html_attrs()` gets all attributes.
24#'
25#' @inheritParams html_name
26#' @param name Name of attribute to retrieve.
27#' @param default A string used as a default value when the attribute does
28#'   not exist in every element.
29#' @return A character vector (for `html_attr()`) or list (`html_attrs()`)
30#'   the same length as `x`.
31#' @examples
32#' html <- minimal_html('<ul>
33#'   <li><a href="https://a.com" class="important">a</a></li>
34#'   <li class="active"><a href="https://c.com">b</a></li>
35#'   <li><a href="https://c.com">b</a></li>
36#'   </ul>')
37#'
38#' html %>% html_elements("a") %>% html_attrs()
39#'
40#' html %>% html_elements("a") %>% html_attr("href")
41#' html %>% html_elements("li") %>% html_attr("class")
42#' html %>% html_elements("li") %>% html_attr("class", default = "inactive")
43#' @export
44#' @importFrom xml2 xml_attr
45html_attr <- function(x, name, default = NA_character_) {
46  xml_attr(x, name, default = default)
47}
48
49#' @rdname html_attr
50#' @export
51#' @importFrom xml2 xml_attrs
52html_attrs <- function(x) {
53  xml_attrs(x)
54}
55
56#' Get element children
57#'
58#' @inheritParams html_name
59#' @examples
60#' html <- minimal_html("<ul><li>1<li>2<li>3</ul>")
61#' ul <- html_elements(html, "ul")
62#' html_children(ul)
63#'
64#' html <- minimal_html("<p>Hello <b>Hadley</b><i>!</i>")
65#' p <- html_elements(html, "p")
66#' html_children(p)
67#' @importFrom xml2 xml_children
68#' @export
69html_children <- function(x) {
70  xml_children(x)
71}
72