document.getElementsByTagName() is available only when the page (or possibly part of it) has been loaded/rendered. Although I know very little about using other languages it seems logical to me that it is too late to change the language of the page(?) once it has been rendered.
The character encoding may also be required:
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
although I suspect this is the default.
If you are only adding a section of the page then you could add lang="es" to, for example, a DIV and then insert the content into this div.