Difference between HTML object and JAVASCRIPT object and how to access and give attributes to javascript objects

0

// //GLOBAL VARIABLES
var box = document.getElementById('game-board');
var cardElement;
var cardsInPlay= [];
var cardNodes = [];
var random;
var cards = [
  {
    rank: 'king',
    pic: 'images/king-of-diamonds.png',
  },
  {
    rank: 'king',
    pic: 'images/king-of-hearts.png',
  },
  {
    rank: 'queen',
    pic: 'images/queen-of-diamonds.png',
  },
  {
    rank: 'queen',
    pic: 'images/queen-of-hearts.png'
  }
];
var cardNodes = [];

//1. CREATE BOARD
function createBoard(){
  for (var i = 0; i < cards.length; i++) {
    cardElement = document.createElement('img');
    cardElement.setAttribute('src', 'images/back.png');
    box.appendChild(cardElement);
    cardElement.addEventListener('click', flipCardAndRandomize);
    cardNodes.push(cardElement); // So now is a HTML node instead JS object (i can use setAttribute now)
  }
}
createBoard();

//2. FLIP CARDS RANDOMLY
function flipCardAndRandomize(){
  //Randomize the deck =>
  random = Math.floor(Math.random()*cards.length);
  this.setAttribute('src', cards[random].pic);
  cardsInPlay.push(cards[random].rank);
  console.log(this);
  match();
}

//3. CHECK IF MATCH
function match(){
  if (cardsInPlay.length === 2) {
    if (cardsInPlay[0] === cardsInPlay[1]) {
      console.log('MATCH');
    } else {
      console.log('TRY AGAIN');
      setTimeout(function(){
        // cardNodes[0].setAttribute('src', 'images/back.png'); // Long way to do it
        // cardNodes[1].setAttribute('src', 'images/back.png');
        // cardNodes[2].setAttribute('src', 'images/back.png');
        // cardNodes[3].setAttribute('src', 'images/back.png');
        cardNodes.forEach(function(node){  // Short way to do it => Executes a function per each array element
          node.setAttribute('src', 'images/back.png');
        });
      },1000);
    }
  }
}
body{
  text-align: center;
  margin: 0;

}

h1 {
  font-family: "Raleway", sans-serif;
  font-weight: 400;
  color: #0d2c40;
  font-size: 45px;
  letter-spacing: 1px;
  margin: 0;
  color: white;
}

p {
  font-family: "Droid Serif", serif;
  line-height: 26px;
  font-size: 18px;
}

a {
  font-family: raleway;
  text-decoration: none;
  color: #F15B31;
  letter-spacing: 1px;
  font-weight: 600;
  font-size: 18px;

}

h2 {
  font-family: raleway;
  font-size: 20px;
  color: #0d2c40;
  letter-spacing: 1px;
  font-weight: 600;
}

header {
  background-color: #F15B31;
  padding: 30px 20px 30px 20px;
}

main {
  width: 850px;
  margin: 35px auto
}

a {
  margin: 0 20px;
  color: white;
}

nav a:hover {
  border-bottom: 2px solid white;
}

nav {
  background-color: #00A6B3;
  padding: 20px 0;
}

img {
  margin: 40px 8px 0 8px;
}

footer {
  text-transform: uppercase;
  padding: 0 20px;
  background-color: #0D2C40;
  color: white;
  letter-spacing: .08em;
  font-weight: 500;
}

.copyright {
  float: left;
}

.message {
  float: right;
}

.clearfix:after {
  visibility: hidden;
  display: block;
  content: " ";
  clear: both;
  height: 0;
  font-size: 0;
}

.name {
  color: #F15B31;
  font-weight: 700;
}
#game-board{
  width: 1200px;
  margin-left: -150px;
}
<!DOCTYPE html>
<html>
   <head>
      <meta charset="utf-8">
      <link href="css/style.css" rel="stylesheet" type="text/css">

      <title>Memory card game</title>
   </head>
   <body>
      <header>
         <h1>Memory Game</h1>
      </header>
      <nav>
         <p><a href="#">INSTRUCTIONS</a><a href="#"> GAME</a></p>
      </nav>
      <main>
         <h2>INSTRUCTIONS</h2>
         <p>Concentration, also known as Match Match, Memory, Pelmanism, Shinkei-suijaku, Pexeso or simply Pairs, is a card game in which all of the cards are laid face down on a surface and two cards are flipped face up over each turn. The object of the game is to turn over pairs of matching cards.</p>
         <div id="game-board" class="board clearfix"></div>
      </main>
      <footer>
          <div class="clearfix">
          <p class="copyright">Copyright 2017</p>
          <p class="message">Created with &hearts; by <span class="name">GA</span></p>
              </div>
      </footer>
    <script src="js/main.js"></script>
   </body>
</html>

Hoal good, I'm new to javascript , and it sure is a silly question. I understand the DOM, to be able to access, with for example = > document.getElementById() to a HTML object and give setAttribute for example since YA IS A HTML OBJECT . My question is: If I create a array , it is a javascript object not a html object , then it tells me is not a function... How do I give attributes to an object created in javsacript, which is not already created in the html. I must = > document.createElement in a loop for example and then apply on that element setAttribute always? Greetings

    
asked by fran 07.12.2017 в 17:14
source

2 answers

-2

Wait for the DOM to load within a

setTimeout(function(){

///tus instrucciones de manipulación van aqui

})
    
answered by 07.12.2017 / 17:30
source
0

You are correct, to be able to use javascript functions designed to change properties of HTML objects, you must have an object of the same type. You get this by calling a DOM object with a document.getElementById for example, or by creating a new object with the document.createElement ();.

What you do here is correct:

cardElement = document.createElement('img');
cardElement.setAttribute('src', 'images/back.png');
box.appendChild(cardElement);

For your specific question it said: "My question is: If I create an array, it is a javascript object not an html object, then it tells me is not a function ..." You can have an Array (Javascript) that contains html objects, as you do here:

function createBoard(){
  for (var i = 0; i < cards.length; i++) {

    /**** IMPORTANTE REDECLARAR LA VARIABLE CON EL "VAR" YA QUE ESTAS DENTRO DE UN CICLO ***/
    var cardElement = document.createElement('img'); 

    /**** LUEGO DE CREAR TU OBJETO, PUEDES AGREGAR LOS EVENTOS Y ATRIBUTOS ****/
    cardElement.setAttribute('src', 'images/back.png');
    cardElement.addEventListener('click', flipCardAndRandomize);

    /*** APENDIZAS AL DOM O A OTRO OBJETO HTML****/
    box.appendChild(cardElement); //AQUI APENDIZAS AL DOM O A OTRO OBJETO HTML

    /*** CUANDO LO GUARDAS EN EL ARRAY DE JAVASCRIPT, TU OBJETO SIGUE ESTANDO COMO REFERENCIA, Y PUEDES CAMBIAR SUS ATRIBUTOS LLAMANDO AL ARRAY Y SU POSICIÓN***/
    cardNodes.push(cardElement);

    /*** CREO QUE AQUÍ ESTA EL PROBLEMA, YA QUE PARA APUNTAR A TU OBJETO DENTRO DEL ARRAY, DEBES UTILIZAR LA POSICION DE TU OBJETO EN EL ARRAY ***/
    cardElement[0].setAttribute('src', 'images/back.png');
  }
}
    
answered by 07.12.2017 в 17:57