Changing the CSS property of a single table cell's innerHTML

I have a question that may seem silly, but I'm going to ask it anyway.

Currently, I am iterating through a list of strings that follow the format "1H 20MIN" and adding them to table cells using the innerHTML property like so:

for (i = 0; i < list.length; i++) { 
    myTable.rows[1].cells[i].innerHTML = list[i];   
}

My intention is to display the numbers (in this case 1 and 20) in one font style and the text (H and MIN) in a different font style.

Is there a way to achieve this, or do you have any suggestions on how to restructure my code/table to make it possible?

Thank you!

Answer №1

Separate the numbers and non-numbers using span elements with appropriate class names, then customize their appearance using CSS.

For example, you can put the digits into spans like this:

myTable.rows[1].cells[i].innerHTML = list[i].replace(/\d+/g, "<span class=num>$&</span>");

...and then apply styles to .num.

Here's an illustration:

var str = "1H 20MIN";
document.getElementById("ex").innerHTML = str.replace(/\d+/g, "<span class=num>$&</span>");
div {
  font-family: sans-serif;
  color: green;
}
.num {
  font-family: serif;
  color: blue;
}
<div id="ex"></div>

Answer №2

To start, one can utilize a programmatic approach to detect the numeric character groups and then appropriately generate spans:

var exampleString = '1H 20MIN';
var spanGroupsArray = [];
var htmlString = '';

function extractSpanGroups(inputString) {
  var groupsArray = [];
  var workingGroup = {
    isNumeric: false,
    items: []
  }

  inputString.split('').forEach(function(letter) {
    processCharacter(letter, workingGroup, groupsArray);
  });

  groupsArray.push({
    text: workingGroup.items.join(''),
    isNumeric: workingGroup.isNumeric
  });

  groupsArray.splice(0, 1); //remove the first empty item;

  return groupsArray;
}

function processCharacter(letter, workingGroup, groupsArray) {
  if (workingGroup.isNumeric === isNumeric(letter)) { 
    workingGroup.items.push(letter);
  } else { 
    groupsArray.push({
      text: workingGroup.items.join(''),
      isNumeric: workingGroup.isNumeric
    });

    workingGroup.isNumeric = isNumeric(letter);
    workingGroup.items = [letter];
  }
}

function isNumeric(letter) {
  return !isNaN(parseFloat(letter)) && isFinite(letter);
}

function convertToHtml(groupsArray) {
  var htmlOutput = '';

  groupsArray.forEach(function(group) {
    if (group.isNumeric) {
      htmlOutput += '<span class="mathy">' + group.text + '</span>'
    } else {
      htmlOutput += '<span class="charactery">' + group.text + '</span>'
    }
  });

  return htmlOutput;
}

spanGroupsArray = extractSpanGroups(exampleString);
htmlString = convertToHtml(spanGroupsArray);
document.getElementById('container').innerHTML = htmlString;
/* #christmas */

.mathy {
  color: red;
}

.charactery {
  color: green;
}
<div id="container">
  <!-- pretend this is a row or cell or w/e -->
</div>

Answer №3

To enhance the code, you can modify it to display numbers and letters in separate spans with customized classes.

I will provide a code illustration later as I am currently on my mobile device. Nevertheless, the result would appear similar to this:

<span class='time'>1<span class='letters'>HR</span> 20<span class='letters'>MIN</span> </span>

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

Managing the closest element depending on the selected option in Angular 5

My task involves accessing the nearest element of a dropdown. The HTML below includes multiple dropdowns and input boxes. When selecting options from the dropdown, I need to enable or disable the input box closest to it. <div class="form-block" *ngFor= ...

Troubleshooting a VueJS Problem: Updating $data in the mounted hook

Revision This snippet of Component.vue was extracted from a larger web application where I made a mistake that had significant consequences, all because of a small change I didn't initially notice. An important distinction exists between the followi ...

Tips for creating a stylish scrollbar in a React Material-Table interface

Currently, I am utilizing the react material-table and looking to implement a more visually appealing scroll-bar instead of the default Pagination option. Although I have experimented with the react-custom-scroll package, it has not produced the desired ...

Is using async/await with setState() in React.js the best approach for handling asynchronous operations?

By utilizing async and prevState, I found a solution to console.log the correct state of the page immediately after updating it. As I delved into backend development, I took the time to understand how async operations function. This led me to experiment w ...

The daily scripture quote from the ourmanna.com API may occasionally fail to appear

I've been trying to display the daily verse from ourmanna.com API using a combination of HTML and JS code, but I'm encountering an issue where the verse doesn't always show up. I'm not sure if this problem is on the side of their API or ...

Explore the comparison feature with jQuery's combobox

I am attempting to compare values from an array with values in a combobox using jQuery, but I am encountering difficulties. My array is structured like this: (value 1, value 2,...) names separated by commas (Example: john smith, peter pan). On the other h ...

Utilizing Tailwind CSS for creating a responsive layout on a Next.js application

I'm just getting started with Tailwind CSS and I decided to build the user interface of my nextjs application using a "mobile first" approach like everyone suggests. I got the flex direction and background color working perfectly on mobile screens, so ...

Changing the position of an image can vary across different devices when using HTML5 Canvas

I am facing an issue with positioning a bomb image on a background city image in my project. The canvas width and height are set based on specific variables, which is causing the bomb image position to change on larger mobile screens or when zooming in. I ...

Excessive HTML and CSS overflow stretching beyond the boundaries of the page on the right

It seems like the issue lies with div.ü and div.yayın, as they are causing overflow on the right side of the page. When these elements are removed, the overflow issue goes away. Are there different positioning codes that can be used to prevent this? d ...

CSS - starting fresh with animations

I am facing an issue with a CSS animation that I created. Everything seems to be working correctly, but I need to complete it by setting the input type to reset the animation. Below is the CSS code snippet that should reset the animation: $('button& ...

Using jest.fn() to simulate fetch calls in React

Can anyone explain why I have to include fetch mock logic within my test in order for it to function properly? Let's take a look at a simple example: Component that uses fetch inside useEffect and updates state after receiving a response: // Test.js ...

The Ajax form's malfunction is attributed to JSON, as it throws a parser error indicating a SyntaxError. Specifically, the JSON.parse function encounters an unexpected end of data at line 1, column 1

I understand that this is a commonly asked question, but I have tried all the solutions provided and none of them have worked for me. My specific issue is that I am unable to load a JSON response from the server using AJAX. Here's the setup: my "scrip ...

Every iteration and vertical lines

<?php $arr = range(1,mt_rand(40,120)); ?> <table> <?php foreach ($arr as &$value) { echo '<tr><td>' . $value . '</td></tr>'; } ?> </table> This script generates a sequence of n ...

Vue.js2 - Detection of Observer in Array

A question for beginners in vue.js. I am trying to display data using the CanvasJS Library that is received via websocket. Everything works fine with the data until I introduce vue components into the mix. Let me clarify: export default { data() { r ...

What is the best way to insert a React component or raw HTML into another React component?

Dealing with raw HTML markup returned from an AJAX call can be tricky in React. I've tried using dangerouslySetInnerHTML, but React just throws errors when I do. It's like trying to navigate through a maze. After some trial and error, I decided ...

Is it a bad idea to incorporate JavaScript functions into AngularJS directives?

I came across this snippet of code while working with ng-repeat: <div ng-show="parameter == 'MyTESTtext'">{{parameter}}</div> Here, parameter represents a string variable in the $scope... I started exploring if it was possible to c ...

What is the best way to incorporate a minimum width and maximum width in CSS that add up to 100% when necessary?

Can anyone help me find CSS rules that can set a fixed width for an element (width: 500px) but also allow it to be responsive with max-width: 100% if the container is narrower than the element? I saw this example and it works perfectly: .elem { width: 60 ...

Guide to building a straightforward line graph using JSON data from a server

When I retrieve price change data from an API endpoint using axios, the response I receive is in the following format: 0: (2) [1639382650242, 48759.49757943229] 1: (2) [1639386250855, 49131.24712464529] 2: (2) [1639389730718, 48952.65930253478] 3: (2) [163 ...

What is the proper way to address the error message regarding requestAnimationFrame exceeding the permitted time limit?

My Angular application is quite complex and relies heavily on pure cesium. Upon startup, I am encountering numerous warnings such as: Violation ‘requestAnimationFrame’ handler took 742ms. Violation ‘load’ handler took 80ms. I attempted to resolve ...

What is the best way to utilize RxJs for streaming HostListener events?

Although I've found plenty of resources on binding Angular HostListeners, I'm curious about using RxJs to stream it instead: @HostListener('document:click', ['$event']) handleClick(event: Event) { // etc } I want to cre ...