Search code examples
javascriptjqueryimagenested-loops

Javascript get image src from table


I have a table with images inside every cell. I need to get the image src from the individual cell. Table creation is dynamic so the cell's id is incremented from 1 upwards. Here is a sample of my code:

var i = 0;
for (h = 0; h < height; h++) {
    for (w = 0; w < width; w++) {
        var src = null;
        if (document.querySelector("#gridcells grid1 img").src === null) {
            src = "random";
        } else {
            src = document.querySelector("#gridcells grid{i} img").src;
        }
        alert(src);
        i++;
    }
}

When doing this however, it produces an error - "cannot read property of src null". I have uploaded more of the source code so you can see it running here:

https://jsfiddle.net/oecc4gpj/4/

Thanks


Solution

  • You can use each to loop over all the images:

    $('#gridcells img').each(function() {
        if ( !$(this).attr('src')) ) {
            $(this).attr('src', 'random');
        }
    });
    

    Demo: https://jsfiddle.net/tusharj/oecc4gpj/2/