jQuery Question

How to check every div block for image

How to check every block for image, and if it is empty, load image inside.

My try:

function showFile(e) {
var files = e.target.files;
var a = 1;
for (var i = 0, f; f = files[i]; i++) {
if (!f.type.match('image.*')) continue;
var fr = new FileReader();

fr.onload = (function(theFile) {

return function(e) {

$('.tra').each( function() {
var $this = $(this);
if ( $this.find('img').length === 0 ) {
$this.append('<img src="'+e.target.result+'">');
} else {
alert("You can select only 5 images");


document.getElementById('photo').addEventListener('change', showFile, false);

After upload image, i want to show this image:


<div class="tra full_photo">
<div class="tra mini_photo">
<div class="tra block_mini_photo block_mini_photo2"></div>
<div class="tra block_mini_photo block_mini_photo3"></div>
<div class="tra block_mini_photo block_mini_photo4"></div>
<div class="tra block_mini_photo block_mini_photo5"></div>
<input type="file" name="photo[]" id="photo" class="upload_true" accept="image/jpeg,image/png,image/gif" multiple>

But after loading, all the blocks are filled

Answer Source

You shold do this:

return function(e) {

        var tra = $('.tra');
        var one = false;

        // test each single div
            if($(this).find('img').length <= 0 && !one){
              $(this).append('<img src="'+e.target.result+'">');
              one = true;

            alert("You can select only 5 images");

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download