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;
}
If your
<script>is in the<head></head>section of your website, then it will start to execute before the page has loaded, and thereforefree_shippingandsalewill not exist in the DOM.Try doing the following, which will make your code happen once the page has finished loading…
This can also be done using the jquery library, but my knowledge of it is exceedingly limited.