I am creating an extremely basic javascript version of tic tac toe. I have already set up the board utilizing a table and assigning borders appropriately.
When the player makes a move an X is placed within the box, and when the computer goes an O.
However my issue is trying to decide if the cell has been “used” meaning that there already exists an X or O within.
Is there a function in javascript which can check for contents within an HTML element or can anyone think of another way to do this? I considered using an array of 9, holding x or o and checking this way, but I ran into the issue of figuring out how to pass the cell number to that function to update the array.
I’m new to javascript so if either of these possibilities exist please let me know or if you have any suggestions of your own!
Use
textContentandinnerTextto get the text of an element.Example:
Explanation:
Since IE8- uses
innerTextand Firefox usestextContent(with other browsers choosing either one side or both), you need to check both properties. We make use of JavaScript’s logical or operator||to check both properties in one line.text = el.textContent || el.innerTextwill storeel.textContentintextif there is atextContentproperty. If there is not atextContentproperty (or iftextContentis the empty string or just whitespace), then it will try to storeinnerTextin thetextvariable. Finally, we use|| ''to set it to the empty string if neithertextContentnorinnerTextcould be found *.* This is only necessary if
textContentwas the empty string/whitespace andinnerTextdid not exist, in which case both would be falsey. Rather than lettextbeundefined, we store the empty string''instead.If you would like to check to see if HTML is in an element rather than text (this would be helpful if you are using image elements for your X and O) you can use
innerHTML. This is standard for all browsers!