text/html
will be set as content type:"
I have not tried your code but if JavaScript fails in one result document but not in another then one reason could be that the JavaScript is written for text/html documents (as which static .html or htm documents are ususally served) while the code does not work right with XHTML served as application/xml or application/xhtml+xml.
So I would first check whether your RESTXQ where the script doesn't work is served as text/html or with an XML MIME type like the two ones I have mentioned, in the latter case I would indeed expect script attempts like
a = document.createElement("DIV")
to fail to achieve to create the right element as X(HT)ML is case-sensitive and works with a namespace so you would rather need
a = document.createElementNS("http://www.w3.org/1999/xhtml", "div")
in an X(HT)ML served with an XML mime type context.
So I think your XQuery code lacks %output:method("xhtml") e.g.
declare
%rest:path("/demo-autocomplete")
%rest:GET
%output:method("xhtml")
function f:demoAutocomplete() as element() {