0

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>
peter hany
  • 43
  • 1
  • 9
  • Have you considered [jQuery](http://jquery.com/)'s [`fadeOut`](http://api.jquery.com/fadeout/) function? You are doing it wrong with JavaScript. Check the console. – Script47 Aug 07 '16 at 20:55

2 Answers2

2

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;
}
Community
  • 1
  • 1
Bamieh
  • 10,358
  • 4
  • 31
  • 52
  • 2
    "returns an array" — no, it returns a live HTMLCollection, not an array. – Quentin Aug 07 '16 at 20:57
  • I didnt want to dive deep in my answer, however HTMLCollections are array-like object similar to arguments, they have object like properties, but can be accessed by index like arrays – Bamieh Aug 07 '16 at 20:59
  • thanks ,, but , what about if i want to apply my function on all images which are is the document ! – peter hany Aug 07 '16 at 21:37
  • updated the comment have a look – Bamieh Aug 08 '16 at 07:28
0

In javascript,

document.getElementsByTagName('img')

returns a nodelist.

If you want the first item in that nodelist, you need to write:

document.getElementsByTagName('img')[0]
Rounin
  • 27,134
  • 9
  • 83
  • 108