You should not be using JS to do the things you are trying to do. Maybe you are trying to do some PHP type things(I have never used PHP). I am no expert on DOM or JS, (I write back-end applications using Java and C#) but can you utilize the document object without having started the html or head tags?
Use this for your script tags as well - <script type="text/javascript">







