Search code examples
javascriptgetelementbyidappendchildcreateelement

Javascript Create Element in Two Divisions


I want to create an iframe using javascript and then insert it into two divisions both having id "fblike". I tried to use the following code but it did not work.

<script type="text/javascript">
  (function(){
    var fb = document.createElement('iframe');
    fb.src = 'http://www.facebook.com/plugins/like.php?href='+encodeURIComponent(location.href)+'&amp;locale=en_US&amp;send=false&amp;layout=button_count&amp;width=90&amp;show_faces=false&amp;action=like&amp;colorscheme=light&amp;font=verdana&amp;height=21';
    fb.scrolling = 'no';
    fb.frameborder = '0';
    fb.style = 'border:none; overflow:hidden; width:90px; height:21px;';
    fb.allowTransparency = 'none';
    document.getElementsById('fblike')[0].appendChild(fb);
  })();
</script>

I know there must be some mistake(s) in the code because I have very little knowledge of javascript. Any one please help me!! Thanks

UPDATE: Thanks for your help :) I updated the code to remove the mistakes. Now the following code works for me:

<script type="text/javascript"> 
  (function(){
    var fb = document.createElement('iframe');
    fb.src = 'http://www.facebook.com/plugins/like.php?href='+encodeURIComponent(location.href)+'&locale=en_US&send=false&layout=button_count&width=90&show_faces=false&action=like&colorscheme=light&font=verdana&height=21';
    fb.style.cssText = 'border:none; overflow:hidden; width:90px; height:21px;';
    fb.frameBorder = '0';
    fb.scrolling = 'no';
    fb.allowTransparency = 'true';
    document.getElementById('fbabove').appendChild(fb.cloneNode(true));
    document.getElementById('fbbelow').appendChild(fb.cloneNode(true));
  })();
</script>

Solution

  • You should not have an id attribute with an equal value on the same page. Fix that first, otherwise document.getElementById() is never going to work properly (it only ever returns one element) and document.getElementsById() (with an s) does not exist.