"Utilize the style attribute to modify the appearance based on the

I was the original asker of this question, but I failed to provide a clear description which led to not getting an answer. However, I will now explain everything here. Essentially, I am looking for a JavaScript function that can identify a class with a specific prefix on any element within the entire document. Let's consider the following HTML markup as an example:

 <body class="c:bg-#008eff">
  <h1 class="c:bg-#ff5c5c">Hello, <span class="c:bg-white">World !</span></h1>

In the above example, we have a common prefix c:bg- in all the classes. I envision a function understand() that can:

(1) Identify all classes with the prefix c: in an HTML document.

(2) Determine what comes after the c: prefix, such as c:bg- indicating a CSS background property and c:text- representing a CSS color property, among others.

(3) Extract and set the value, for instance, c:bg-#008eff signifies a CSS background property with the value #008eff.

(4) Strip away the c:bg-, c:text-, etc. prefixes from the obtained class string and utilize the remaining part to define styles.

We have our example:

<body class="c:bg-#008eff">
  <h1 class="c:bg-#ff5c5c">Hello, <span class="c:bg-white">World !</span></h1>

In the output of the above code in a browser window, we would see the body with a background of #008eff, h1 with a background of #ff5c5c, and span with a white background.

Another example:

<body>
  <h1 class="c:text-#ff5c5c c:pad-20px">Hello, <span class="c:text-#008eff c:mar-20px">World !</span></h1>

In the output of the above code in a browser window, the h1 element would have a color of #ff5c5c and a padding of 20px while the span would have a color of #008eff and a margin of 20px.

Lastly, it is crucial to note that if the same type of code is repeated, the last one will overwrite the first one. For example:

<h1 class="c:bg-blue c:bg-red">Hello</h1> 
<!-- Executes red background -->

I hope my explanation is clearer now! Can the understand() function become a reality?

Thank you for taking the time to read this.

Answer №1

When approaching a more efficient solution, one option is to utilize the data-* attribute:

const applyStyle = el => el.style.cssText = el.dataset.style;

document.querySelectorAll("[data-style]").forEach(applyStyle);
<h1 data-style="color:#f0b; background:#0bf;">TEST</h1>
<h1 data-style="color:#b0f; background:#fb0;">TEST</h1>

https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/cssText

Alternatively, another approach could be:

const props = {
  bg: 'background',
  text: 'color',
  pad: 'padding'
};

const understand = el => {
  const c_classes = [...el.classList].filter(name => name.startsWith('c:'));
  return el.style.cssText = c_classes.map(k => {
    const pv = k.split('c:')[1].split('-');
    return `${props[pv[0]]}:${pv[1]}`;
  }).join(';');
}

const ELZ = document.querySelectorAll("[class^='c:'], [class*=' c:']");
ELZ.forEach(understand);
<h1 class="test c:bg-yellow c:pad-20px c:text-#0bf bla">
    Hello, <span class="c:bg-red">World !</span>
</h1>

Answer №2

Although it is recommended to use the data-* attribute, here is a workaround using regex to extract and apply classes:

function assignStyle(element, property, val) {

  const properProperty = shortToProper[property] || property;

  element.style[properProperty] = val;
}

const shortToProper = {
  "bg": "background",
  "text": "color",
  "pad": "padding",
  "mar": "margin"
};

const pattern = /c:(\w+)-([^\s]*)/g;

const elems = document.querySelectorAll(`[class^='c:'],[class*=' c:']`);

elems.forEach(elem => {
  const matches = elem.className.matchAll(pattern);

  for (const match of matches) {
    assignStyle(elem, match[1], match[2]);
  }

});
<body class="test c:bg-#008eff">
  <h1 class="c:bg-#ff5c5c">Hello, <span class="c:bg-white">World !</span></h1>
  <h1 class="c:text-#ff5c5c c:pad-20px">Hello, <span class="c:text-#008eff c:mar-20px">World !</span></h1>
  <h1 class="c:bg-blue c:bg-red">Hello</h1>
</body>

Alternatively, here's an improved approach using data-c:

function assignStyle(el, style, value) {

  const styledProperty = shortToProper[style] || style;

  el.style[styledProperty] = value;
}

const shortToProper = {
  "bg": "background",
  "text": "color",
  "pad": "padding",
  "mar": "margin"
};

const pattern = /(\w+)-([^\s]*)/g;

const elements = document.querySelectorAll('[data-c]');

elements.forEach(element => {
  const matches = element.dataset.c.matchAll(pattern);

  for (const match of matches) {
    assignStyle(element, match[1], match[2]);
  }

});
<body data-c="bg-#008eff">
  <h1 data-c="bg-#ff5c5c">Hello, <span data-c="bg-white">World !</span></h1>
  <h1 data-c="text-#ff5c5c pad-20px">Hello, <span data-c="text-#008eff mar-20px">World !</span></h1>
  <h1 data-c="bg-blue bg-red">Hello</h1>
</body>

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

Determine the byte size of the ImageData Object

Snippet: // Generate a blank canvas let canvas = document.createElement('canvas'); canvas.width = 100; canvas.height = 100; document.body.appendChild(canvas); // Access the drawing context let ctx = canvas.getContext('2d'); // Extrac ...

Encountering ReferenceError while running production build with Webpack

After upgrading to webpack 3.10.0 and Babel 6.26, I managed to fix my dev build but encountered issues with the prod build that I can't seem to resolve. This is the error message I am seeing: ERROR in ./src/index.js Module build failed: ReferenceErr ...

How can I make the columns in Next.js / Tailwind expand horizontally first instead of vertically?

Recently, I decided to customize the Next.js Image Gallery starter for some hands-on experience in full stack development with Next.js. My goal was to create a chronological photo gallery of a recent trip, but encountered an issue where the responsive colu ...

Shape with a dark border div

Having some trouble with creating this particular shape using CSS border classes. If anyone can assist in making this black box shape using Jquery, it would be greatly appreciated. Check out the image here. ...

Toggle the visibility of table rows based on a specific class using a checkbox

I am currently working on a code that displays the results of a query in a table format. I would like to have the ability to click on certain elements to show or hide them. I know this can be achieved using toggle and CSS, but I keep encountering obstacles ...

What is the best way to display the current scroll percentage value?

I'm trying to update this code snippet import React from 'react' const App = () => { function getScrollPercent() { var h = document.documentElement, b = document.body, st = 'scrollTop', sh = 'scrollHeight ...

Tips for utilizing maps in a react component within a Next.js application

I received an array of data from the backend that I need to display on a React component. home.js import Head from "next/head"; import Header from "../src/components/Header"; import * as React from 'react'; import { styled } ...

Adding a class to a navigation item based on the route path can be achieved by following

I am currently working on a Vue.js project and I have a navigation component with multiple router-links within li elements like the example below <li class="m-menu__item m-menu__item--active" aria-haspopup="true" id="da ...

Code snippet for a click event in JavaScript or jQuery

I initially wrote the code in JavaScript, but if someone has a better solution in jQuery, I'm open to it. Here's the scenario: I have multiple questions with corresponding answers. I want to be able to click on a question and have its answer dis ...

Obtain a string of characters from different words

I have been trying to come up with a unique code based on the input provided. Input = "ABC DEF GHI" The generated code would look like, "ADG" (first letter of each word) and if that is taken, then "ABDG" (first two letters o ...

display a loading spinner for number input fields in HTML5

In my HTML5 project, I am currently utilizing a numeric control (input type="number"). The default behavior displays the spinner (up and down arrows) only on hover. Is there a way to make the spinner permanently visible using CSS or another method? ...

Leveraging the Meteor Framework for Application Monitoring

Exploring the potential of utilizing Meteor Framework in a Monitoring Application. Scenario: A Java Application operating within a cluster produces data, which is then visualized by a Web Application (charts, etc.) Currently, this process involves using ...

Is it possible to absolutely position an element using its own bottom edge as a reference point?

Looking to achieve precise positioning of an element just off the top of the screen, specifically a sliding menu. Utilizing position: absolute and top: 0px is straightforward, but this aligns the element based on its top edge. Is there a way to achieve th ...

What could be causing the issue of PHP not receiving this multidimensional array through Ajax?

Having an issue with receiving a multidimensional array in PHP after posting it from JS using Ajax: $.ajax({ type: 'post', url: 'external_submit.php', dataType: "json", data: { edit_rfid_changes_submit ...

Images are failing to show up in the iPhone design

Encountering issues with displaying images on an iPhone? You can replicate the problem by minimizing your browser window horizontally. Here is a link showcasing the problem: here. To temporarily fix this, try zooming out the browser (Ctrl+-). You can see a ...

Having difficulty interpreting the json data retrieved from the specified url

<html> <body> <script src='http://code.jquery.com/jquery-1.10.2.min.js'></script> <script> $(document).ready(function () { $.ajax({ type: 'GET& ...

Emphasize the URL of the current page and navigate up one level

I have a list of links in my navigation. I want the current page's link to be highlighted, as well as the parent page's link one level up. For example: All pages: /blog, blog/careers, blog/authors Page: /blog/author Highlight: /blog/author, /blo ...

Exploring the power of async/await in conjunction with loops

My JavaScript code is designed to extract content from HTML pages and perform a crawling operation. However, the issue arises with asynchronous execution due to a request function. I attempted to utilize Promises and async & await to address this probl ...

The "loose" mode is not resolving the issue with the lack of support for the experimental syntax 'classProperties' that is currently disabled

Error Message: The experimental syntax 'classProperties' is currently not enabled Even after trying the suggested solutions, I still encounter the error during re-building. Click here for more information on the experimental syntax 'classP ...

A Guide to Importing CSV Data Into a Datatable

Is there a way to efficiently import data from a CSV file and display it in a table using the datatables plugin? Currently, I have a fixed table structure: <table id="myTable" class="table table-striped" > <thead> ...