I'm trying to get cardImage (face image) to replace the images/back.png image when clicked

var cards = [
  {
    rank: 'queen',
    suit: 'diamonds',
    cardImage: 'images/queen-of-diamonds.png'
  },
  {
    rank: 'queen',
    suit: 'hearts',
    cardImage: 'images/queen-of-hearts.png'
  },
  {
    rank: 'king',
    suit: 'diamonds',
    cardImage: 'images/king-of-diamonds.png'
  },
  {
    rank: 'king',
    suit: 'hearts',
    cardImage: 'images/king-of-hearts.png'
  }
]
var cardsInPlay = [cards]
var checkForMatch = function () {
//   this.cardImage.setAttribute(src)
  this.src.setAttribute(cardImage)
  if (cardsInPlay[0] === 2) {
    window.alert('You found a match!')
  } else {
    window.alert('Sorry, try again')
  }
}
var flipCard = function () {
  console.log('flipCard() ran')
  var cardId = this.getAttribute('data-id')
//   cardId.getAttribute('data-id')
  checkForMatch()
  cardsInPlay.push(cards[cardId])
  console.log('User flipped ' + cards[cardId].rank)
  console.log('User flipped ' + cards[cardId].cardImage)
  console.log('User flipped ' + cards[cardId].suit)
}
function createBoard () {
  var gameBoard = document.getElementById('game-board')
  for (var i = 0; i < cards.length; i++) {
    var cardElement = document.createElement('img')
    cardElement.setAttribute('src', 'images/back.png')
    cardElement.setAttribute('data-id', i)
    cardElement.addEventListener('click', flipCard)
    gameBoard.appendChild(cardElement)
  }
}
/*var cardId = flipCard(0)
flipCard(2)*/
createBoard()

I think the problem is likely around here:
this.src.setAttribute(cardImage)

This is not how setAttribute is used, you should pass in the attribute name as well as the value. Like setAttribute('src', 'imagepath').
But at the same time you are using this.src. So something is wrong here. You should use one or the other but not both. this.src = "imagepath" or use this.setAttribute('src', 'path').

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.