document.createElement / document.body.appendChild not creating / writing div where executed

Danny S picture Danny S · Feb 3, 2012 · Viewed 17.5k times · Source

I have a div with the ID 'headercontent' and I have a script that will write a link amongst the others if javascript is enabled on the users system, but also has a backup using noscript just in case the user does not have javascript enabled.

The code runs fine and the 'a' element is written when executed but the problem is that the code is not written in the div it is executed in. It writes it outside of the 'headercontent' div and it ignores the class style completely, even though it is written in the rendered code. I'm not too worried about the styling/class because I can just add a style attribute to the element and get it written by javascript if necessary, but I'm more concerned about why its writing the code outside of this div.

My code is:

<div id="headercontent">
    hey, this is a div.
    <a href="#" class="button">This is a link</a>
    <a href="#" class="button">This is another link</a>

    <script type="text/javascript">
        writeask()
        function writeask() {
         var writeaskbox = document.createElement('a');
         writeaskbox.href = 'javascript:askbox()';
         writeaskbox.className = 'button';
         writeaskbox.innerHTML = 
             ['Ask'].join(' ')
         document.body.appendChild(writeaskbox);
        }

        function askbox(){
         var askbox = document.getElementById('askbox')
         if (askbox.style.display == 'none') {
          askbox.style.display = 'block'
          askbox.style.height = '150px'             
         } else {
          askbox.style.display = 'none'
          askbox.style.height = '0px'
         }
        }
    </script>
    <noscript><a href="/ask" class="button">Ask</a></noscript>
</div>

How do I get the writeask() function to create this a element in the same div it is executed in? So that the final output is:

<div id="headercontent">
    hey, this is a div.
    <a href="#" class="button">This is a link</a>
    <a href="#" class="button">This is another link</a>
    <a href="javascript: askbox()" class="button">Ask</a>
</div>

Instead of:

<div id="headercontent">
    hey, this is a div.
    <a href="#" class="button">This is a link</a>
    <a href="#" class="button">This is another link</a>
</div>
<a href="javascript: askbox()" class="button">Ask</a>

I'm still a beginner with javascript so I'm rather puzzled now. If anyone could help, that would be well appreciated.

Thank you in advance. Dan.

Answer

caleb picture caleb · Feb 3, 2012

Instead of

document.body.appendChild(writeaskbox);

use

document.getElementById("headercontent").appendChild(writeaskbox);