0

I want to show a card within my html page from a file. I am trying to get two randomly selected values from two arrays then concantenating them together to create the src for the image. When i try to do this i keep getting this error:

Uncaught TypeError: Cannot set property 'src' of null at blackJack.js:14

HTML Code

<!DOCTYPE html>
<html lang ='en'>
<head>
<meta charset="UTF-8">
<script src="blackJack.js"></script>
<title>Section 2: Javascript Language Basics</title>
</head>

<body>
<h1>Section 2: Javascript Language Basics</h1>

<img id="myImg" src="/Users/victorcollins/Desktop/Computer Science/IA/Coding/Playing Cards/PNG-cards-1.3/2spades.png" width="107" height="98">
</body>



</html>

Javascript

var suits, cards, players, randCards, randSuit;

suits = ['hearts', 'diamonds', 'spades', 'clubs'];
cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
players = [];

randCards = Math.floor(Math.random() * 13) + 1;
var randSuit = suits[Math.floor(Math.random() * suits.length)];
image = randCards + randSuit;
console.log(randCards+randSuit);
console.log(image);

document.getElementById("myImg").src = '/Users/victorcollins/Desktop/Computer Science/IA/Coding/Playing Cards/PNG-cards-1.3'+image+'.png';
robinCTS
  • 5,458
  • 14
  • 27
  • 37

1 Answers1

0

Uncaught TypeError: Cannot set property 'src' of null at blackJack.js:14

You element must be loaded into DOM before you can access the same, so put this script tag just before ending body tag.

<html lang ='en'>
   <head></head>
   <body>
      <img id="myImg" src="/Users/victorcollins/Desktop/Computer Science/IA/Coding/Playing Cards/PNG-cards-1.3/2spades.png" width="107" height="98">
      <script src="blackJack.js"></script>
   </body>
</html>
gurvinder372
  • 61,170
  • 7
  • 61
  • 75
  • That HTML is invalid. ` – Quentin Dec 01 '17 at 14:47