Search code examples
javascriptimageonloadtagname

Simple JS code bug


why dose not it work ? !! i want to make images fade out when it is loaded , i know that this can be done by jQuery , but i wanna know where is the bug in this code.

<img src="http://1.bp.blogspot.com/-M03SoTLlJ4k/Vfwvq2dz42I/AAAAAAAAD9I/o-xN8x6HL2Y/s1600-r/Untitled-1%2B%25281%2529.png" onload="loadimage()" id="imageid"/>
<style>
#imageid {
opacity:0;
transition:1s;
}
</style>
<script>
function loadimage(){
document.getElementsByTagName("img").style.opacity="1"
}
</script>

Solution

  • getElementsByTagName returns a NodeList not a single DOM node, hence you need to do getElementsByTagName('img')[0] for example to get the first img, then apply the styles on that element.

    Update

    select all images

    if you want to select all the images and apply styling to them

    function loadimage(){
       var imgElements = document.getElementsByTagName('img');
       for(var i=0, l=imgElements.length; i < l; i++) {
          imgElements[i].style.alpha = 1;
       }
    }
    

    only currently loaded image (preferred by me)

    function loadimage(){
      this.style.alpha = 1;
    }