Search code examples
javascripthtmlimagegetelementbyidappendchild

Place an image in div using Javascript


I am trying to build a Baccarat game, and want to place an image of each card in a div that is nested in a li - list item. I have an empty image tag in a div with an id tag, and have created a Card Object in Javascript that has a "name", "suit" and "value". The "name" and "suit" relate to the file name for each card (ie. AceSpades, TenDiamonds, JackClubs...etc.) located in the local "images" folder as a ".png". When I run the code I am getting a "Cannot read property 'appendChild of null".

Below is an excerpt from the javascript code I have so far to give an idea of where I am coming from:

function card(name, suit, value) {
  this.name = name;
  this.suit = suit;
  this.value = value;
}

var cardsInDeck = [];
var suits = ["Spades","Hearts","Clubs","Diamonds"];
var names = ["Ace","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King"];
var values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0];
var card;

for (var i = 0; i < suits.length; i++) {
    for (var j = 0; j < names.length; j++) {
        cardsInDeck.push(new card(names[j], suits[i], values[j]));
    }
}

var b1, b2, b3, p1, p2, p3;

var drawOne = function() {
   var card = cardsInDeck.pop();
   return card;
}

var initialDealOut = function() {
  b1 = drawOne();
  p1 = drawOne();

  b2 = drawOne();
  p2 = drawOne();
}

initialDealOut();

var b1n = b1.name + b1.suit;

The code that I am trying to use to place the image in the div is:

var b1Image = function() {
  var div = document.getElementById('b1');
  var image = document.createElement('img');
    image.src = "image/" + b1n + ".png";
  div.appendChild(image);
}

b1Image();

The core HTML for where I want to place the images is:

<div class="row">
  <ul class="cards">
    <li class="box">
      <div class="card" id="b1">
        <img src="">
      </div>
    </li>
  </ul>
</div>

I have searched out a number of responses relating to similar questions, but of the answers that were given none seem to work the way I've tried implementing them. I am new to programming, so I am sure this is an easy fix, but I am more than likely not approaching it correctly.

I apologize in advance for any confusion this questions brings with it and appreciate any assistance anyone can lend to help solve this.


Solution

  • Edit: The code was updated.

    You are trying the run the function b1Image() before the page has loaded. Using an event handler or adding onload="b1Image()" to the body tag would run the code after the page has loaded. Also, don't run the function in your script file or script tag.

    Before Edit:

    Running var b1n = b1.name + b1.suit; without initializing b1 could be the source of problems.

    Run the function initialDealOut to initialize it before assigning it b1n if you haven't.