Would this still work if the element name was more complex like "foo/bar/hat"
No, the predicate [name() = 'foo/bar/hat']
would not select anything, because foo/bar/hat
is a path expression, not an element name. Variables in XPath hold values, not expressions or expression fragments - it's not like a shellscript (or other macro language) where variables are expanded and the expanded expression is then re-parsed.
XQuery does not have any general capability for constructing an expression dynamically as a string and then evaluating it. Many products have extension functions to do this, often called xx:eval() or xx:evaluate(). XSLT 3.0 has an xsl:evaluate instruction.