Chessboard in pure js

  • A+
Category:Languages

I began js 3 days ago at school, I had some C basics before so the main problem here would be the syntax (I think).

The goal is to produce a chessboard, 8x8 black and white square, but I can't get the code to show anything. What am I missing ?

(the html just have the script src="./x.js" part and the "body" part)

document.body.onload = addElement.innerHTML;  function addElement() {      var newTable = document.createElement("table");     for (var i = 1; i < 9; i++) {         var newTr = document.createElement('tr');         for (var j = 1; j < 9; j++) {             var newTd = document.createElement('td');             if (i % 2 == j % 2) {                 newTd.className = "white";             } else {                 newTd.className = "black";             }             newTr.appendChild(newTd);         }         newTable.appendChild(newTr);     }      document.body.appendChild(newTable);      document.getElementByClass("black").style.backgroundColor = "black";     document.getElementByClass("white").style.backgroundColor = "white";     document.getElementByTag("newTd").style.width = "25px";     document.getElementByTag("newTd").style.height = "25px"; } 

 


There are few mistakes in your code use getElementsByClassName instead of getElementByClass and use getElementsByTagName instead of getElementByTag.

Also you need to loop over each selected elements.

Use window.onload = addElement; or you can simply call addElement(); after function declaration completes.

window.onload = addElement;  function addElement() {   var newTable = document.createElement("table");   for (var i = 1; i < 9; i++) {     var newTr = document.createElement('tr');     for (var j = 1; j < 9; j++) {       var newTd = document.createElement('td');       if (i % 2 == j % 2) {         newTd.className = "white";       } else {         newTd.className = "black";       }       newTr.appendChild(newTd);     }     newTable.appendChild(newTr);   }    document.body.appendChild(newTable);   var i = 0;   for (i = 0; i < document.getElementsByClassName("black").length; i++) {     document.getElementsByClassName("black")[i].style.backgroundColor = "black";   }   for (i = 0; i < document.getElementsByClassName("white").length; i++) {     document.getElementsByClassName("white")[i].style.backgroundColor = "white";   }   for (i = 0; i < document.getElementsByTagName("td").length; i++) {     document.getElementsByTagName("td")[i].style.width = "25px";     document.getElementsByTagName("td")[i].style.height = "25px";   }  }

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: