Move some logic into functions.
Add tests. Allow namespaced elements.