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

What is the process of exporting a module that has been imported in ES6?

Here are 3 code snippets: // ./src/index.ts const myApp = { test: 1, ... } export default myApp // ./src/app.ts import myApp from './src/index' export default myApp // ./index.vue import { example } from './src/app.ts' console.l ...

Generating alternate list items

I'm attempting to design a list style that resembles the one depicted in the image linked below: https://i.stack.imgur.com/U7vMw.jpg My issue is that when I try to add borders, they end up applying to the entire structure. .styled-list { list-st ...

How can global variables be effectively shared and edited between two separate runs of JavaScript nodes?

The primary function contained in main.js is as follows: var nLastPingTime = 0, nLastPingNumber = 0; module.exports = { compareData: function(nPingTime, nLastPingNumber){ nLastPingTime = nPingTime; nLastPingNumber = nLastPi ...

issue in jquery: ajax promise not returning any value

My code snippet: var testApp = (function($){ var info = [{ "layout": "getSample", "view": "conversations", "format": "json", }]; var Data = 'default'; function fetchInfo(opt) { return new Promis ...

Upon including the enctype attribute as "multipart/form-data" in my form and submitting it, the form redirects to a different page

My website has two main pages: The first page is admin.php <?php session_start(); if (!isset($_GET['page'])){ $_GET['page'] = 'home'; }//end if include_once(dirname(__FILE__)."/function.php"); ?> <?ph ...

CSS equal-width table columns

My goal is to create evenly spaced columns like in this example. It used to work in a previous version, but now I can't seem to figure out what's causing the difference. Even when copying the old HTML into a jsfiddle and applying the same CSS, it ...

When is it necessary to use JSON.parse(JSON.stringify()) with a Buffer object?

I am currently working with Buffer objects in my existing code. let dataObject = JSON.parse(JSON.stringify(data)); At first glance, it seems like the above code is redundant and doesn't achieve much. However, replacing it with: let dataObject = data; ...

Struggling with getting the JavaScript, scss, and CSS television animation to turn on and off properly? Seeking assistance to troubleshoot this

After finding this javascript code on Codepen and seeing that it worked perfectly in the console there, I tried to run it on my computer with jQuery but it didn't work outside of Codepen. Even when attempting to use it on JSfiddle or compile the SCSS ...

Vuetify: Utilizing condition-based breakpoints

Here is the layout that I am working with: https://i.stack.imgur.com/qlm60.png This is the code snippet that I have implemented: <template> <v-card> <v-card-text> <v-container grid-list-xl fluid class="py-0 m ...

What is the best way to utilize date-fns for formatting a date retrieved from an API?

After receiving data from an API in the 'yyyy-MM-dd' format, I encountered a display issue when trying to convert it to 'dd-MM-yyyy'. How can I properly adjust the date format without disrupting the table display? onMounted(async () =& ...

"What is the best way to retrieve the id of the element that triggered a JavaScript onclick

I'm facing an issue with my GridView where I have information displayed in each row. When a user clicks on a row, more related information is supposed to be shown in a separate DIV. However, I am unable to target the specific row when trying to change ...

Error encountered: The JSONP request to https://admin.typeform.com/app/embed/ID?jsoncallback=? was unsuccessful

I encountered an issue with the following error message: Error: JSONP request to https://admin.typeform.com/app/embed/id?jsoncallback=? Failed while trying to integrate a typeform into my next.js application. To embed the form, I am utilizing the react-ty ...

Encountering an issue while attempting to implement Redux Toolkit alongside the MUI ToggleButtonGroup component

The error message initially started as: Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. When I attempted to update the Redux state using a dispatcher, the handleChange function suddenly showed an e ...

Issue with Material-UI tab when using a datatable within it's content

I implemented the Simple Tabs feature from Material-UI with a Tab containing a Datatable using React-Data_Table. However, I noticed that this particular tab is not responsive like the others when the table is full. Empty Full Here's a snippet of th ...

The issue of transform scale not functioning properly in conjunction with background clip and gradients in CSS

Looking to transform a div with the transform: scale(-1,1) property while using background-clip: text on the text within it. However, this causes the text to disappear. Here's what I've attempted: .reverse { transform: scale(-1, 1); } .gr ...

When the Bootstrap navbar is collapsed, clicking on it does not result in it opening

I'm attempting to create a collapsible navbar for smaller screens that expands when a button is clicked. However, upon clicking the button, nothing happens and I'm unsure why. <nav class="navbar navbar-expand-lg navbar-light" style="backgro ...

Error found in Twitter Bootstrap popover plugin: `this.isHTML` function is missing

I took the example directly from their website: http://jsfiddle.net/D2RLR/631/ ... and encountered the following error: this.isHTML is not a function [Break On This Error] $tip.find('.popover-title')[this.isHTML(title) ? 'html&apos ...

Tips for effectively implementing a custom theme alongside a component library that utilizes Material UI without the need to apply it to every single component

What is the correct way to utilize a custom theme with a component lib that utilizes Material UI without wrapping every single component? import { createMuiTheme } from '@material-ui/core/styles'; const theme = createMuiTheme({ palette: { ...

steps for marking comments as read or unread by multiple users

I'm working on a development blog for my project and I'd like to add a feature where users can mark comments as unread until they view them. For example, if an admin posts a comment, all users in that project should see it as unread. Can anyone ...

Leveraging Async / Awaits with Promise

Within my code, I have a specific promise chain that follows this structure: myPromise() .then(getStuffFromDb) .then(manipulateResultSet) .then(manipulateWithAsync) .then(returnStuffToCaller) An issue arises when working within the mani ...