Discover how to apply unique styles to specific HTML elements using their index values in jQuery

In the process of creating a party game similar to Tambola or Housie, I am faced with the challenge of automatically detecting and highlighting the numbers called out on each ticket in the game. For instance, if number 86 is announced, I aim to visually distinguish it by changing the font color or background color on tickets numbered 2 and 3 accordingly. The complexity arises from the fact that these tickets are presented as HTML elements copied from another source where they are initially generated. Hence, I seek a solution that can pinpoint these numbers and apply individual styling to them. Any assistance provided would be greatly valued.

The tables displayed under "current nos." in the image represent tambola tickets containing random numbers generated using a particular function. It's important to note that these numbers are not within my direct control. The primary goal is to identify whether the numbers declared by the game host (e.g., 1, 3, 45, 46, 48, 49, 50, 86, 87, 90) exist in each ticket and modify the appearance of those specific numbers on the respective tickets.

To aid in identifying these numbers easily, I have included spaces between each number in the table, positioned before and after the numerical values. Thus, querying $(#tickets).text() results in an output such as:

  1. 1 32 54 72 81... and so forth (referencing the image).

Below is a snippet of the code I've developed for this task:

<body>
<div id='tickets' style="font-size: 40px">
            </div>
    
<script>

var array = [];
var num = [1,3,45,46,48,49,50,86,87,90]     //numbers retrieved from local storage
var clonetkt = localStorage.getItem("checktiks");    //replicating ticket data as HTML from external webpage

for (i = 1; i <= 90; i++) {
            array.push(i);
 }

 for (a = 0; a <= num.length; a++) {
                for (b = 0; b < 90; b++) {
                    if (array[b] == num[a]) {
                        array[b] = 0;
                    }
                }
            }

function recreateTable() {
            $('#tickets').html(clonetkt);   //rendering ticket tables as HTML
            
            var z;
            var n;
            if (array[i - 1] == 0) {
            z= "  " + i + "  ";    //inserting spaces to match table elements
            n = $('#tickets').text();
            $('#tickets').each(function(){    //attempting to match table elements but only effective for first occurrence
            n = $('#tickets').text().indexOf(z);
            if (n >=0){
            console.log($('#tickets').text()[n+1] + $('#tickets').text()[n+2]);     //verification of number detection in #tickets
            }
            });
        }
        }
        recreateTable();

</script>
</body>

Your support and expertise on this matter will be highly appreciated!

https://i.sstatic.net/CiLUx.png

Access the .js file for ticket generation via the following link: https://drive.google.com/file/d/1CxmEO1jBOVft6y68BZyuXBAAby7lXwi2/view?usp=drivesdk

Answer №1

Once you have stored the ticket value that needs to be highlighted in an array, you can use it to highlight other tickets as well. To iterate through every ticket, you can utilize a each loop and compare the values of td with the array. If they match, you can add a class like highlight to apply CSS styling to that specific td.

Check out the Demo Code snippet below:

var array = [];
var num = [1, 3, 45, 46, 48, 49, 50, 86, 87, 90];

for (i = 1; i <= 90; i++) {
  array.push(i);
}

for (a = 0; a <= num.length; a++) {
  for (b = 0; b < 90; b++) {
    if (array[b] == num[a]) {
      array[b] = 0;
    }
  }
}

function recreateTable() {

  var boardHTML = "<table border='1'>";
  
  for (i = 1; i <= 90; i++) {
    if (i == 1 || i == 11 || i == 21 || i == 31 || i == 41 || i == 51 || i == 61 || i == 71 || i == 81) {
      boardHTML += "<tr>"; 
    }
    
    if (array[i - 1] === 0) {
      boardHTML += "<td bgcolor='lightgreen' id='td" + i + "'><font color='red'>" + i + "</font></td>";
    } else {
      boardHTML += "<td id='td" + i + "'>" + i + "</td>";
    }

    if (i == 10 || i == 20 || i == 30 || i == 40 || i == 50 || i == 60 || i == 70 || i == 80 || i == 90) {
      boardHTML += "</tr>";
    }
  }
  
  boardHTML += "</table>";
  document.getElementById('board').innerHTML = boardHTML;

}
recreateTable(0);

function addColorToTickets() {
  for (i = 1; i <= 90; i++) {
    if (array[i - 1] === 0) {
      z = " " + i + " ";
      
      $('#tickets table tr').each(function() {
        $(this).find('td').each(function() {
          if ($(this).text() === z) {
            $(this).addClass('highlight');
          }
        })
      })

    }
  }
}
addColorToTickets();

.highlight {
  background-color: lightgreen;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="housiebd">
  <h1>
    <center> HOUSIE BOARD </center>
  </h1>
  <table id="hboard" style="margin: 20px auto;">
    <tr>
      <td id="board" style="text-align: center; font-size: 32px;">
      </td>
    </tr>
  </table>
</div>
<br>
<center>
  <div id='cnos' style="font-size: 20px">
    Current Nos.: 1, 3, 45, 46, 48, 49, 50, 86, 87, 90
  </div>
</center><br>

<center>
  <div id="div" style="font-size: 24px;
margin: 20px auto;
padding: 10px;
text-align: center;">
  </div>
</center>
<!--demo tickets-->
<div id="tickets">
  <table id="tiktable0" style="border: 1px solid black; margin: 20px auto; width: 500px; height: 250px;">
    <thead>
      <tr>
        <th colspan="9">1. Ajparag</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td style="border: 1px solid black;"> 2 </td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"> 39 </td>
        <td style="border: 1px solid black;"> 42 </td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"> 69 </td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"> 84 </td>
      </tr>
      <tr>
        <td style="border: 1px solid black;"> 5 </td>
        <td style="border: 1px solid black;"> 16 </td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"> 56 </td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"> 75 </td>
        <td style="border: 1px solid black;"> 86 </td>
      </tr>
      <tr>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"> 17 </td>
        <td style="border: 1px solid black;"> 29 </td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"> 48 </td>
        <td style="border: 1px solid black;"> 57 </td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"> 87 </td>
      </tr>
    </tbody>
  </table>
  <table id="tiktable1" style="border: 1px solid black; margin: 20px auto; width: 500px; height: 250px;">
    <thead>
      <tr>
        <th colspan="9">2. Apj</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td style="border: 1px solid black;"> 6 </td>
        <td style="border: 1px solid black;"> 11 </td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"> 41 </td>
        <td style="border: 1px solid black;"> 52 </td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"> 84 </td>
      </tr>
      <tr>
        <td style="border: 1px solid black;"> 8 </td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"> 37 </td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"> 53 </td>
        <td style="border: 1px solid black;"> 65 </td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"> 86 </td>
      </tr>
      <tr>
        <td style="border: 1px solid black;"> 9 </td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"> 28 </td>
        <td style="border: 1px solid black;"> 38 </td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"> 73 </td>
        <td style="border: 1px solid black;"> 89 </td>
      </tr>
    </tbody>
  </table>
</div>

Answer №2

Instead of nesting two loops within each other, I would opt for using two separate loops for better performance. Utilizing the modulo operator can streamline the creation of <tr> tags in a more efficient manner. Keep in mind that I adjusted my approach to not rely on LocalStorage variables due to unspecified contents in your code.

Furthermore, it is advisable to eliminate deprecated elements like <center> and embrace CSS classes (e.g., td { text-align: center; }) instead.

var clonetkt = '1 6 8 11 43 59'; //localStorage.getItem("checktiks");
let $tickets = $('#tickets');

function highlightMatches() {
  let matches = $tickets.html().split(' ');
  for (let match of matches) {
    $('#td' + match).addClass('highlight');
  }
}

function recreateTable() {
  $tickets.html(clonetkt); //cloning tickets from another webpage in this div (i.e. 'tickets')

  var boardhtml = "<table border='1'>";
  for (let i = 1; i <= 90; i++) {
    if (i % 10 === 1) {
      boardhtml += "<tr>"; //creating housie board at top
    }

    boardhtml += "<td id='td" + i + "'>" + i + "</font></td>";

    if (i % 10 === 0) {
      boardhtml += "</tr>";
    }
  }
  boardhtml += "</table>";
  document.getElementById('board').innerHTML = boardhtml;

  highlightMatches();

  /*
  var prenoary = JSON.parse(localStorage.getItem("previousNos"));
  $('#pnos').append(prenoary + "  ");
  var crrtnoary = JSON.parse(localStorage.getItem("currentNos"));
  $('#cnos').append(crrtnoary + "  ");
  */
}

recreateTable();
body {
  font-family: 'Open Sans', sans-serif;
}
.highlight {
  background: green;
  color: white;
}

h1,
td,
div.info {
  text-align: center;
}

#hboard {
  margin: 20px auto;
}

#hboard #board {
  text-align: center;
  font-size: 32px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="housiebd">
  <h1>
    HOUSIE BOARD
  </h1>
  <table id="hboard">
    <tr>
      <td id="board">
      </td>
    </tr>
  </table>
</div>

<div class="info">
  <div id='pnos' style="font-size: 40px">
    Previous Nos.:
  </div>
</div>

<div class="info">
  <div id='cnos' style="font-size: 40px">
    Current Nos.:
  </div>
</div>

<div class="info">
  <div id='tickets' style="font-size: 40px">
  </div>
</div>

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

When the child state changes the parent state, useEffect may not be triggered for the first time

Component for children export const FlightRange = (props) => { const [value, setValue] = useState(props.value); return ( <> <input type='range' min={1000} max={50000} step="500&quo ...

What is the best way to split two divs in this manner?

Is there a way to split two divs like this in such a manner using TailwindCSS? Alternatively, what would be the CSS code for dividing these two divs? I am struggling with this concept and cannot wrap my head around how it can possibly be achieved. ...

IntelliJ coverage for backend JavaScript

Is it possible to analyze code coverage in IntelliJ without using a browser? http://www.jetbrains.com/webstorm/webhelp/monitoring-code-coverage-for-javascript.html Though there are tutorials by JetBrains on code coverage, they all seem to require a browse ...

Inline styles are effective, but external stylesheets are not functioning properly (see JsFiddle for reference)

http://jsfiddle.net/xw0vvo9e/4/ Trying to specify a background color for the navBar. In the provided jsfiddle, the CSS includes: div .navBar { width: 100%; height: 45px; background-color: #FF0000; top: 0px; position: fixed; } However, the background ...

How to toggle tooltip visibility dynamically using Angular 2

I am working with elements within an ngFor loop. Some of these elements have tooltips, while others do not. I am experiencing an issue where when using the code snippet below: <div ngFor="let item of items"> <div [title]="item.title"> Ele ...

Ways to display the page's content within a div container utilizing Jquery

I am attempting to display the content of a URL page (such as ) within a <div> using JQuery, but so far I have been unsuccessful. Here is an example of what I am trying to achieve: <div id="contUrl"> .. content of google.fr page </div> ...

What techniques does Angular2 use to handle dependency injection?

When working with Angular2 components, I know that to inject a dependency, you simply annotate an argument in the constructor, like how ThingService is injected here. However, what I am wondering is how Angular actually knows what to inject at runtime. A ...

Creating a countdown timer that is determined by the word count of a specific <div> element

What I have: A unique countdown timer that starts at 3 seconds and counts down to 0s. <div class="phrase"> This is a statement.</div> <p> <div style='font-family: Arial; font-size: 12px; color:gray'> <br><s ...

Three.js dynamic bone animation: bringing your project to life

Can transformations be applied to the bones of a 3D model in three.js to create a dynamic animation? I attempted to move and rotate the bones of a SkinnedMesh, but the mesh did not update. loader = new THREE.JSONLoader(); loader.load(&apos ...

The jade code is causing an error to be displayed

The following Jade code seems to be malfunctioning. head script(src='http://d3js.org/d3.v3.min.js') script(src='http://dimplejs.org/dist/dimple.v2.1.0.min.js') body script(type='text/javascript') var svg ...

Load an external URL and load a file from the local directory using Electron

For an upcoming art exhibition, I have a video installation that consists of large videos (several GBs) and an online hosted web application. To conserve bandwidth during the exhibition, I am considering packaging the videos into an electron app. This way ...

Multiple web pages utilizing Angular app/widget

I have successfully built a chat application similar to Google Hangouts. However, I am facing a challenge with the angular app/widget running on other pages when URL's are changed, causing the app to either remain fixed or restart on the new web page. ...

Exploring the Power of JQuery with Hover Effects and SlideToggle

I was struggling to keep the navbar displaying without it continuously toggling when my pointer hovered over it. I just wanted it to stay visible until I moved my pointer away. <script> $(document).ready(function(){ $(".menu-trigger").hover(funct ...

What is the best way to assign a value to a class variable within a method by referencing the 'this' keyword?

Is there a way to set the state of this Ionic react app when displaying the outcome of a reset service? I am facing challenges with using this.setState({resetSuccess}) within a method due to scope issues. (Details provided in comments) Here is the relevan ...

Controller unable to process JSON data as intended

Good evening, I am attempting to create an editable gridview with jQuery. When the edit button is clicked, the row should change to an editable row. However, I am encountering a problem when trying to parse values to the controller, as the value is not bei ...

Trouble with Add To Cart feature in React app due to issues with Context API

I have been following a tutorial located here. I followed the steps exactly and even checked the code on the related github repository, which matches. However, when I try to add a product to the cart by clicking the button, the state does not update. In Re ...

jQuery accordion is currently in the expanded state

I'm currently in the process of creating an accordion using jQuery, following this example: http://docs.jquery.com/UI/Accordion The structure remains the same: <div id="accordion"> <h3><a href="#">First header</a></h3& ...

Switch out text and calculate the frequency of letters in a given string

I have a string that looks like this: "061801850010300-09/A/B". My goal is to replace all "/" with "-" and also change "A" to "1" and "B" to "2". My objective is to assign each letter in the alphabet a numerical value - for example, A as 1, B as 2, C as 3 ...

Removing a outside div element based on a dropdown change in ASP.NET jQuery

this is the structure of my unique div <div class="row-fluid"> <div class="span12"> <div style="overflow: auto; width: 90%;" class="goleft"> <div style="display: inline-block; width: 200px;"> ...

Acquire an array of Worksheet names in JavaScript by utilizing ActiveX

How can I retrieve a comprehensive list of all available sheet names from my Excel file using the ActiveX Object? I am aware that the code Excel.ActiveWorkBook.Sheets provides access to the sheets. However, how do I obtain an array containing the NAMES of ...