Jaynill Gopal
Jaynill Gopal

Reputation: 47

How to add images as cells in table with Javascript

I'm trying to add an image to my table for each individual cell using Javascript as part of a Connect4 game that I have to create for my assignment. Could I please get some help with this?

Here's the function that I am trying to add the image in: (the stuff that's been commented out is what I've tried to use but failed

function generateTable()
    {
        var brd = document.getElementById("board");

        var x =document.createElement("IMG");
        x.setAttribute("src","block.png");
        x.setAttribute("height","10%");
        x.setAttribute("width","10%");
        x.setAttribute("alt","block.png");

        var body = document.getElementsByTagName("body")[0];

        var tbl = document.createElement("table");
        var tblBody = document.createElement("tbody");

        var maxCol= 7;
        var maxRow = 6;

        for(var x=0;x<maxRow;x++)
        {
            var row = document.createElement("tr");

            for(var y=0;y<maxCol;y++)
            {
                var cell = document.createElement("td") ;
            /*  cell= "<img src='board.png' alt='board' height='10%' width = '10%'>";*/
        /*   var cellImg= document.createElement("board");
                cell.appendChild(cellImg);*/
                            //var cellText = document.createTextNode("jhgfbcjk");
                            //cell.appendChild(x);

                row.appendChild(cell);
            }       

            tblBody.appendChild(row);           
        }

        tbl.appendChild(tblBody);
        body.appendChild(tbl);
        /*tbl.setAttribute("border","2");*/
}

Upvotes: 2

Views: 3606

Answers (2)

Brett DeWoody
Brett DeWoody

Reputation: 62773

Use cell.innerHTML = '<img src="http://placehold.it/40x40?text=IMG" width="20" height="20" />';

function generateTable() {
  var brd = document.getElementById("board");
  var body = document.getElementsByTagName("body")[0];
  var tbl = document.createElement("table");
  var tblBody = document.createElement("tbody");

  var maxCol = 7;
  var maxRow = 6;

  for (var x = 0; x < maxRow; x++) {
    var row = document.createElement("tr");

    for (var y = 0; y < maxCol; y++) {
      var cell = document.createElement("td");
      cell.innerHTML = '<img src="http://placehold.it/40x40?text=IMG" width="20" height="20" />';
      row.appendChild(cell);
    }

    tblBody.appendChild(row);
  }

  tbl.appendChild(tblBody);
  brd.appendChild(tbl);
}
  
  generateTable()
<div id="board"></div>

Upvotes: 2

user7582130
user7582130

Reputation:

Within your generateTable() function, try adding:

function generateTable()
{
    var whateverrow=document.getElementById("yourId").rows[0];
    x.innerHTML="<img src='URL' alt='whatever'/>";
}

This should set the inner HTML of a new cell to a HTML img element.

Upvotes: 0

Related Questions