Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get text from HtmlTableCellElement

Working on a simple jquery tic-tac-toe project. I'm trying to iterate through the board and save the values of each cell in an array, but can't figure out how to access the text inside each td. I've tried .text() and .value() but both return undefined

index.html:

<html>
    <head>
        <title>jQuery Tic Tac Toe</title>
    </head>
    <body>
        <table border="1" cellpadding="40">
            <tr>
                <td data-x="0" data-y="0">Test</td>
                <td data-x="1" data-y="0"></td>
                <td data-x="2" data-y="0"></td>
            </tr>
            <tr>
                <td data-x="0" data-y="1"></td>
                <td data-x="1" data-y="1"></td>
                <td data-x="2" data-y="1"></td>
            </tr>
            <tr>
                <td data-x="0" data-y="2"></td>
                <td data-x="1" data-y="2"></td>
                <td data-x="2" data-y="2"></td>
            </tr>
        </table>
        <div id="games"></div>
        <div id="message"></div>
        <button id="save">Save Game</button>
        <button id="previous">Show Previous Games</button>
    </body>
</html>

tic-tac-toe.js:

function getBoard(){
    board = [];
    $.each($("td"), function(index, cell){
        board.push(cell); //Need to return contents of cell
    });
    alert(board);
}
like image 679
Brian Menard Avatar asked Dec 25 '22 05:12

Brian Menard


2 Answers

Try this:-

Use this cell.innerHTML instead of cell

        function getBoard() {
            board = [];
            $.each($("td"), function (index, cell) {
                board.push(cell.innerHTML); //Need to return contents of cell
            });
            alert(board);
        }

Hope this will help you.

like image 99
Sharique Ansari Avatar answered Dec 26 '22 19:12

Sharique Ansari


You need to use .text()

 $.each("td", function(index, cell) {
   board.push($(cell).text()); //Need to return contents of cell
 });
like image 23
Anoop Joshi P Avatar answered Dec 26 '22 18:12

Anoop Joshi P