I'm doing an Ajax query that pulls back a JSON array filled with ~50 urls to images. I then use a forEach
on the array to produce a <div>
nested with other <div>
, with one of those <div>
holding an <img>
element in where I set the src
equal to the current url in the forEach
iteration.
The catch is that some of the urls are dead, and result in broken <img>
elements ( you know, with the little images of a ripped file?). So what I do is, during the iterations, when I create my <img>
element, I set the onerror
attribute equal to "$(this).closest('.gramDiv').remove()"
, which attempts to delete a certain <img>
parent element and all of that parent's childrens. This works, but I feel like it's kinda hacky, and not best practice. Is there more standardized way of doing this?
$(document).ready(function(){
console.log("Ready");
function adder(data,status){
data.forEach((url,index)=>{
let attrObj = {
src: url,
alt: 'photo ' + index,
onerror: "$(this).closest('.targetDiv').remove()"
};
let img = $('<img>').attr(attrObj);
let targetDiv = $('<div></div>').addClass('target');
let picDiv = $('<div></div>').addClass('picDiv').append(img);
let component = targetDiv.append(picDiv);
$('#bodyDiv').append(component);
})
}
$.ajax({
url:'https:/blahblahblah.json',
dataType: 'json',
success: adder,
timeout: 3000,
error: function(){ alert('error retrieving')}
});
})