Steps to reproduce: 1: Visit https://www.chess.com/play/computer 2: Paste JS code in the console
Expected results: Pieces are printed by their square number ascendingly
Actual results:
Uncaught TypeError: newPieces.sort is not a function error is thrown
JS code:
pieces = ["r","n","b","q","k","p"];
colors = ["w","b"];
squareTemplate = "square-";
boardTemplate = "chess-board.layout-board";
function updatePieces(){
return document.querySelectorAll("chess-board.layout-board .piece");
}
function getFen(isFlipped){
}
function evalMove(){
}
console.log("Starting up ...");
const board = document.querySelector(boardTemplate);
let newPieces = [];
newPieces = updatePieces();
newPieces.sort(function(a,b){return a.classList[2].split('-')[1] - b.classList[2].split('-')[1]});
let fenRows = [];
for(i=0;i<newPieces.length;i++){
let classList = newPieces[i].classList;
let pieceColor = classList[1][0];
let pieceType = classList[1][1];
let pieceSquare = classList[2].split('-')[1];
//console.log(" Piece color is: " + pieceColor + " it is: " + pieceType + " and it is in: " + pieceSquare);
if(pieceColor == 'w'){
pieceType.toUpperCase();
} else {
pieceType.toLowerCase();
}
fen
}
So, basically JS is trying to tell me that is not an array, well, if it is not an array, then I am born in Bangladesh, because it is let newPieces = [];
updatePieces function in not returning an array, and sort method only work on array's, please first check updatePieces() function output
sort() is a method located on the Array.prototype which is what you want to use where as querySelectorAll() returns a static NodeList representing a list of the document's elements that match the specified group of selectors not an array. this is why your getting your exception. if you wish to use sort, you need to convert it into an array.
You can convert it to an array using array.from
const pieces = document.querySelectorAll("chess-board.layout-board .piece");
const arr = Array.from(pieces);