philss / floki

Floki is a simple HTML parser that enables search for nodes using CSS selectors.
https://hex.pm/packages/floki
MIT License
2.05k stars 155 forks source link

Add a "children" utility function #215

Closed augnustin closed 4 years ago

augnustin commented 5 years ago

Given a node, I can't see a simple way to access its children.

Shouldn't there be a Floki.children method for that?

philss commented 5 years ago

@augnustin you can pattern match the node like this:

{type, attrs, children} = node

Or you can use the Kernel function elem/2 to fetch in the third position:

elem({"a", [], ["hello"]}, 2)

Do you think this solves the problem?

augnustin commented 5 years ago

Thanks for getting back.

I am aware of those possibilities, but correct me if I'm wrong, I think a node can also be a string, hence the correct way to safely get children would be:

  def children(node) do
    case node do
      node when is_tuple(node) -> elem(node, 2)
      _ -> nil
    end
  end

wouldn't it?

I agree this is more of a utility function since it is trivial to write, but it would help, especially for piping. Eg.

root_node |> Floki.children() |> List.first |> Floki.children() |> Enum.filter(fn {tag_name, _attributes, _children } -> tag_name == "pre"  end) |> Floki.children()

which is something pretty common on the DOM.

(By the way, I'd be in favour of having Floki.attributes(node) too, and Floki.is(node, selector) that would return true if the selector matches :smile: ).

philss commented 4 years ago

hi @augnustin! Sorry for the delay. I think @msramos just added this functionality according to what you was describing. Can you check if it's enough? I'm going to close this issue. Feel free to re-open it if you want. Thanks!

augnustin commented 4 years ago

Great! Thanks guys