Q:

What is wrong with the JS code and let me know if the code can be improve

Getting TypeError: document.getElementById("free_shipping") is null
This is what im trying ---
I just want to make sure that these two particular div show only only my home page . but im getting this error however alerts are working. Let me know if im missing something.
Can i made this code even better as i only have to use JAVACRIPTin this case.
JS CODE
<script type="text/javascript">
var myaddr = location.host;
if(myaddr  == "abc.xy.com")
{
document.getElementById('free_shipping').style.display="visible"; 
document.getElementById('sale').style.display="visible"; 
//alert("I am in if");
}
else{
document.getElementById('free_shipping').style.display="none"; 
document.getElementById('sale').style.display="none"; 
//alert("I am in else");
}
</script>

HTML CODE
    <!--####### Free Shipping Start ##############-->
    <div id="free_shipping">
    </div>
    <!--Free Shipping End-->
    <!--####### Sale Start ####### -->
    <div id="sale">
    </div>
    <!--Sale End-->

CSS CODE
    #free_shipping
    {
    background: url("../images/template/swap_free_shipping.jpg") no-repeat scroll 0 0 transparent;
    height: 112px;
    left: -57px;
    position: relative;
    top: 256px;
    width: 62px;  
    }
    #sale
    {
    background: url("../images/template/swap_sale.jpg") no-repeat scroll 0 0 transparent;
    left: -55px;
    position: relative;
    top: 384px;
    width: 59px;
    height: 79px;

}

A:

If your <script> is in the <head></head> section of your website, then it will start to execute before the page has loaded, and therefore free_shipping and sale will not exist in the DOM.
Try doing the following, which will make your code happen once the page has finished loading...
<script type="text/javascript">
  window.onload = function() {
    var myaddr = location.host;
    if(myaddr  == "abc.xy.com")
    {
      document.getElementById('free_shipping').style.display="visible"; 
      document.getElementById('sale').style.display="visible"; 
      //alert("I am in if");
    }
    else{
      document.getElementById('free_shipping').style.display="none"; 
      document.getElementById('sale').style.display="none"; 
      //alert("I am in else");
    }
 }
</script>

This can also be done using the jquery library, but my knowledge of it is exceedingly limited.

