Tips for using the .innerHTML method to reference multiple indexes

How can I set the .innerHTML for multiple indexes of an array? I currently have an array

let poles = Array.prototype.slice.call(document.querySelectorAll(".pole"));

This array contains 9 empty divs, such as :

<div class="pole" id="1"></div>

When a user clicks on one of these divs, it will display either X or O since it is for a tic-tac-toe game.

I want to achieve something like this :

poles[0][1][2].innerHTML ==='X'

or

poles[0, 1, 2].innerHTML === 'X'

Instead of having to write out every condition individually:

if(poles[0].innerHTML === 'X' && poles[1].innerHTML === 'X' && poles[2].innerHTML === 'X')

Answer №1

We can extract the first 3 items from the array using the slice method, and then check if each item has an innerHTML value of "X" by utilizing the every function:

poles = Array.from(document.querySelectorAll('div > span'))

let first3 = poles.slice(0, 3)

if (first3.every(i => i.innerHTML === 'X')) {
  console.log('Row 1 contains all x')
} else {
  console.log('Row 1 doesn\'t contain all x')
}
<div>
  <span>X</span>
  <span>X</span>
  <span>X</span>
</div>
<div>
  <span></span>
  <span></span>
  <span></span>
</div>
<div>
  <span></span>
  <span></span>
  <span></span>
</div>

If we change one item to have a value of "O" instead of "X", the result will indicate that it does not contain all "X"s:

poles = Array.from(document.querySelectorAll('div > span'))

let first3 = poles.slice(0, 3)

if (first3.every(i => i.innerHTML === 'X')) {
  console.log('Row 1 contains all x')
} else {
  console.log('Row 1 doesn\'t contain all x')
}
<div>
  <span>X</span>
  <span>O</span>
  <span>X</span>
</div>
<div>
  <span></span>
  <span></span>
  <span></span>
</div>
<div>
  <span></span>
  <span></span>
  <span></span>
</div>

A more advanced approach involves creating a function called testWin() that examines the game board for a winning scenario based on the provided parameter, either "X" or "O". Simply call the function with the desired player symbol:

  • Create a function with an array of possible win combinations
  • Iterate over all possible wins
  • Generate a temporary array of elements using map to retrieve 3 elements at a time
  • Determine if every element's innerHTML matches the player symbol passed as a parameter

poles = Array.from(document.querySelectorAll('div > span'))

function testWin(player) {
  // An array containing all possible win scenarios
  let wins = [
    // Horizontal
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    // Vertical
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    // Diagonal
    [0, 4, 8],
    [2, 4, 6]
  ]

  // Loop through each possible win scenario and determine if there is a win
  for (let i in wins) {
    // Retrieve a list of elements from the poles array according to each win combination
    let itms = wins[i].map(key => poles[key])
    // Check if the array represents a valid win
    if (itms.every(itm => itm.innerHTML === player)) {
      return {win: true, line: i, player}
    }
  }
  // Return false if no win was detected
  return {win: false, player}
}


console.log(JSON.stringify(testWin('X')))
console.log(JSON.stringify(testWin('O')))
div > span {
  width: 20px;
  height: 20px;
  display: inline-block;
}
<div>
  <span>X</span>
  <span>O</span>
  <span>O</span>
</div>
<div>
  <span></span>
  <span>X</span>
  <span></span>
</div>
<div>
  <span></span>
  <span></span>
  <span>X</span>
</div>

Answer №2

Here's a snippet of code you can utilize:

let check = true;
for (let i = 1; i < 4; i++) {
   if (elements[i].innerHTML !== "X") {
      check = false;
   }
}
if (check) {
   // Only X values found
} else {
   // Other values besides X present
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

During post-processing, the elimination of lens flares can sometimes lead to an error known as "copyTexImage2D: framebuffer is

After looking at the lens flares example here: , I'm encountering an issue with post-processing this particular scene. The blocks display correctly, but the light sources and lens flares are missing. Additionally, I am receiving several warnings in t ...

Filling out a form within a webpage fetched through a DOMParser

Creating automation software in JavaScript using TamperMonkey. The script performs several AJAX requests that retrieve HTML to be parsed with a DOMParser. Is there a way to submit these forms without opening the newly retrieved HTML on the main page? ...

Is there a way to automatically convert a webpage to a PDF when it is requested?

I'm looking to convert the webpage into a PDF file upon request. Below are the scripts I am using: <script> pdfdoc.fromHTML($('#container').html(), 10, 10, { 'width': 110, ...

What could be causing the state to continuously appear as null in my redux application?

Currently, I am in the process of developing a basic contacts application to gain expertise in React and Redux. The main focus right now is on implementing the feature to add a new contact. However, I have encountered an issue where the state being passed ...

invoke a managed bean to execute JavaScript code

I am facing an issue while trying to clear a hidden form value in a JSF page from a managed bean class. I tried calling a method where I used the following code snippet to call JavaScript, but unfortunately it throws a java.lang.NullPointerException. The c ...

After a successful login, learn how to implement a bottom tab menu in React Native

I'm diving into the world of react-native and finding myself a bit lost when it comes to routing and navigation. I have 4 screens - Login, Register, Home, and Links. The Register and Login screens are all set up, with the ability to navigate back usin ...

Tips for defining a distinct series of key-value pairs in typescript

Having experience with a different language where this was simple, I am finding it challenging to articulate a sequence of pairs: Each pair is made up of two basic elements (such as strings or numbers) Each element may appear multiple times within the lis ...

What could be the reason for my function throwing a TypeError with the message "<function> is not a function"?

Every time I try to call a function that clearly appears to be defined as a function, I continuously receive the error message: TypeError: [function name] is not a function. To demonstrate the issue, here is a simple example: main.ts import someFunction ...

Having trouble with Javascript's JSON.stringify or PHP's json_decode?

I am attempting to send an array from JavaScript to PHP. JavaScript: var json = JSON.stringify(extraFields); url += "&json="+json; PHP: $json = json_decode($_GET['json'], true); foreach($json as $K=>$V){ echo "json".$K . "=" . $V ...

Detecting Scroll on Window for Specific Element using Jquery

I need help troubleshooting my code. I am trying to activate only one item that comes from the bottom of the page, but instead all div elements are getting activated. $(window).scroll(function() { $('.parallax').each(function(e) { if($( ...

The resizing function on the droppable element is malfunctioning on Mozilla browsers

I've been working on making one div both droppable and resizable. Surprisingly, everything is functioning perfectly in Chrome but not in Firefox. If you'd like to see the issue for yourself, here is my jsFiddle demo that you can open in Firefox: ...

What is the most effective way to include JavaScript code in a PDF file?

What is the process for integrating JavaScript code into a PDF document? I am familiar with coding in JavaScript and would like to learn how to add it to a file in order to perform tasks such as displaying the current date or using a combobox. ...

When working with JObject return type, an empty Array will be returned in JSON

When sending a request from Postman which hits the API in the backend, the return type of the method is JObject. I am using JObject.Parse method to parse the string but getting an empty array as a result. Update to Newtonsoft (to version 10) has occurred. ...

Refreshing the view following a model update within an AJAX call in the Backbone framework

I'm struggling with my code as I can't seem to get my view to update after a model change. var ResultLoanView = Backbone.View.extend({ id:"result", initialize: function(){ this.render(); this.on('submissionMa ...

Adjusting the quantity of buttons in real-time following an ajax request

Creating buttons dynamically in an Ajax success function can be a challenge when the number of buttons varies each time. I am able to create the buttons, but since the exact number is unknown, adding the correct number of button listeners becomes tricky. ...

Exploring nested arrays of objects and applying value constraints

Is there a way to iterate through an array and display only 5 items at once, with the option to call a function on click that will add another 20 items? I have an object structured like this: let someObject = [ { data: [ { id: 123, ...

The unique format created by tinyMce is not being displayed

I am trying to customize the style format of my tinyMCE, but I am having trouble getting it to show up. Can anyone suggest what might be going wrong? Where should I place the button "Formats" so that I can choose a specific style? tinyMCE.init({ mod ...

Changing a date string to MM DD format in React without using plain JavaScript

I'm familiar with how to handle this outside of React. My issue is that I have a date string coming from an API within an object, and I need to reformat it. The current format is "2022-12-13T06:00Z" but I want it to display as "December 13". The objec ...

Can you explain the purpose of the fix unwind operation in MongoDB?

Just a heads up - I've included some screenshots after running code on my PC. Even though I've encountered this issue multiple times, I still can't quite wrap my head around it In this MongoDB $unwind tutorial for nodejs at the 11:10 minute ...

Tips for isolating the month values from the res.body.results array of objects with the help of JS Array map()

Looking to adjust the custom code that I have which aims to extract months from a string using regex. It seems like I'm almost there but not quite hitting the mark. When checking the console log, I am getting "undefined" values for key/value pairs and ...