.empty () in javascript, how to do it?

4

I'm using a preview script for images created with jquery, however I want to accomplish it in Javascript Vanilla, I'm looking for a way to override the variableQualquer.empty (); but I did not find, how can I replace this command?

JQuery code

$("#fileUpload").on('change', function () {

    if (typeof (FileReader) != "undefined") {

        var image_holder = $("#image-holder");
        image_holder.empty();

        var reader = new FileReader();
        reader.onload = function (e) {
            $("<img />", {
                "src": e.target.result,
                "class": "thumb-image"
            }).appendTo(image_holder);
        }
        image_holder.show();
        reader.readAsDataURL($(this)[0].files[0]);
    } else{
        alert("Este navegador não suporta FileReader.");
    }
});
    
asked by anonymous 04.05.2017 / 22:21

2 answers

5

The .empty() in this case is simply innerHTML = ''; .

This native JavaScript script might look like this:

var input = document.getElementById('input');
var image_holder = document.getElementById('image-holder');
input.addEventListener('change', function() {

  if (typeof FileReader != "undefined") {
    image_holder.innerHTML = '';
    var reader = new FileReader();
    reader.onload = function(e) {
      var img = document.createElement('img');
      img.src = e.target.result;
      img.className = 'thumb-image';
      image_holder.appendChild(img);
    }
    image_holder.style.display = 'block'; // aqui poderá haver outras variantes para mostrar o elemento
    reader.readAsDataURL(this.files[0]);
  } else {
    alert('Este navegador não suporta FileReader.');
  }
});
    
04.05.2017 / 22:40
5

Sergio's answer is correct, but I'll leave here an alternative that has better performance - useful if you need to optimize your application.

The function below receives a DOM element and removes all child elements from it, one by one, until it is empty:

function empty(el) {
    while(el.children.length) {         // enquanto houver filhos
        el.removeChild(el.children[0]); // remove o primeiro filho
    }
}
    
05.05.2017 / 00:06