Use the element that calling eventlister inside function
How use the element that calling eventlister in a function, to append new element.
Example:
window.onload = function()
{
Array.from(document.getElementsByClassName('image_add_product')).forEach(function(element,index)
{
element.addEventListener("change", input_change, false);
});
};
Now i need to use that element
inside input_change
function, to append a new element span. Using element.parentNode.insertBefore(span, this.nextSibling)
, get error element is not defined
, using this.parentNode.insertBefore(span, this.nextSibling)
, get error Cannot read properties of undefined (reading 'insertBefore')
.
What is the correct way to do that? Pls, see the comments on code.
function input_change(evt)
{
//with this operator i can access the properties of element, but...
var file = this.files[0];
if(file.size > 1572864)
{
console.log("Imagem exede o tamanho máximo permitido de 1,5 MB");
this.value = "";
return false;
}
var reader = new FileReader();
reader.onload = (function(theFile)
{
return function(e)
{
var span = document.createElement('span');
span.innerHTML ="<img src='...'/>";
/*here is the problem
how append span using element as reference*/
this.parentNode.insertBefore(span, this.nextSibling);
};
})(file);
reader.readAsDataURL(file);
return true;
}
Solution 1:
The problem is this
inside the onload of the file is the file, it is NOT the this
outside of it.
document.querySelectorAll('.image_add_product').forEach(function(element) {
element.addEventListener("change", input_change, false);
});
function input_change(evt) {
var elem = this;
var file = elem.files[0];
if (file.size > 1572864) {
console.log("Imagem exede o tamanho máximo permitido de 1,5 MB");
this.value = "";
return false;
}
var reader = new FileReader();
reader.onload = function(e) {
var span = document.createElement('span');
span.innerHTML = "HELLO<img src='...'/>";
elem.parentNode.insertBefore(span, elem.nextSibling);
};
reader.readAsDataURL(file);
return true;
}
<label for="img1">
<input type="file" id="img1" class="image_add_product" >
</label>
<label for="img2">
<input type="file" id="img2" class="image_add_product" >
</label>