0

I was searching for a way to upload and preview and image with JavaScript and found this post : make simple image preview. now, I am a beginner JavaScript programmer and I wanted to know why when I tried to change the line document.querySelector('img[class='preview']'); to "document.getElementsByClass('preview')" it didn't work.

from this:

function filePreview() {
  var preview = document.querySelector('img[class="preview"]');
  var file = document.querySelector('input[type=file]').files[0];
  var reader = new FileReader();

  reader.onloadend = function(){
    preview.src = reader.result;
  }

  if(file){
    reader.readAsDataURL(file);
  }else{
    preview.src = "";
  }
}

to this

function filePreview() {
  var preview = document.getElementsByClassName("preview");
  var file = document.querySelector('input[type=file]').files[0];
  var reader = new FileReader();

  reader.onloadend = function(){
    preview.src = reader.result;
  }

  if(file){
    reader.readAsDataURL(file);
  }else{
    preview.src = "";
  }
}

HTML

  <div class="uploadimg">
    <input type="file" onchange="filePreview()"><br>
    <img src="" height="300" class="preview" alt="Image preview"><br>
    <img src="" height="200" class="preview" alt="2"><br>
    <img src="" height="150" class="preview" alt="3">
  </div>

What I'm trying to do is make 3 previews (Big Medium and Small) by trying to set the image given by the input:file to all three image sources

1 Answers1

0

It should be:

document.getElementByClassName("preview");

And this will ALWAYS return an array of objects, thus, if you only have one DOMElement with a class of "preview", you'd need:

var preview = document.getElementByClassName("preview")[0];

You can read more about this method here: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName

Napoli
  • 1,389
  • 2
  • 15
  • 26