Getting all inline styles from an HTML string using JavaScript

(JavaScript) I am working with an html email template stored as a string. Is there a way to extract all the inline styles used in the template? For instance, if I have this input:

<div style="min-width:300px;max-width:600px;overflow-wrap:break-word;word-wrap:break-word;word-break:break-word;margin:0 auto;" align="center">
  <div style="margin: 0 auto;padding: 20px;">
    <a href="/" style="text-decoration: none;">
       <img src="https://i.ibb.co/KXYtCNT/Logo-wellness-w.png" alt="" width="84px" />
    </a>
  </div>
</div>

I would like the output to be ['min-width','max-width','overflow-wrap','word-wrap','word-break','margin','padding','text-decoration']

I believe using Regex would be the most efficient way, but I am unsure of the exact syntax. I attempted this for tags:

const tagRegex = /<\/?[\w\d]+>/gi;

and this for styles but couldn't get it to work:

const styleRegex = /(.*?)+:[\w\d]+;/;

Answer №1

For a secure approach, utilize the DOMParser:parseFromString() method, as previously suggested by Quentin.

const HTML = `<div style="min-width:300px;max-width:600px;overflow-wrap:break-word;word-wrap:break-word;word-break:break-word;margin:0 auto;" align="center">
  <div style="margin: 0 auto;padding: 20px;">
    <a href="/" style="text-decoration: none;">
       <img src="https://i.ibb.co/KXYtCNT/Logo-wellness-w.png" alt="" width="84px" />
    </a>
  </div>
</div>`;

// Regular Expression explained at: https://regex101.com/r/K4z8M4/1
const CSS_PATTERN = /([\w-]*)\s*:\s*(.*?)(?=\s*(?:;|$))/g;

const parser = new DOMParser();
const doc = parser.parseFromString(HTML, 'text/html');
const domElements = doc.querySelectorAll('body *');

domElements.forEach((e) => {
  if (e.style.cssText != '') {
    console.log('Identified style attribute on <' + e.tagName + '>');
    console.log('Inline CSS = "' + e.style.cssText + '"');
    console.log('Retrieve CSS rules with regular expression:');
    
    const matches = e.style.cssText.matchAll(CSS_PATTERN);
    for (const match of matches) {
      console.log('  ' + match[1] + ': ' + match[2]);
    }
    
    console.log('Affected style rules:');
    for (const [key, value] of Object.entries(e.style)) {
      if ((key + "").match(/^\d+$/)) {
        console.log('  ' + value);
      }
    }
  }
});

As illustrated, a regex was employed to identify the CSS rules. This is because discrepancies were observed between the style attribute of the DOM element and the CSS declarations. For instance, specifying margin: 1em impacts margin-top, margin-right, margin-bottom, and margin-left. However, typically only the margin rule is desired in the list.

If further clarification on the regular expression utilized to split the CSS rules is required, refer to the pattern description here: https://regex101.com/r/K4z8M4/1

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

Getting information from MongoDB using Node.js and Angular

Currently, I am facing difficulty in retrieving data from MongoDB (I'm also using Mongoose) and sending it to Angular in order to populate the ng-repeat list with the retrieved data. I have managed to either display the data on a blank page directly f ...

What is the process for setting default parameters using a recompose, lifecycle HOC?

I've created a custom recompose, lifecycle HOC: import { lifecycle } from 'recompose'; export function myHoc(title) { return lifecycle({ componentDidMount() { console.log(title) } }); } export default my ...

What is the best way to properly format letters with accents (such as French letters)?

I have encountered a challenge where I created a PHP file to display French text and then utilized this text in an AJAX file (specifically the responseText). The issue arises when trying to show the French responseText in an alert using JavaScript, as ac ...

The functionality of PHP in relation to the jQuery post feature seems to be malfunction

After developing the JavaScript functionality for this contact form, below is the HTML structure without any CSS styling included: <!-- Contact Form --> <div class="cws-widget"> <div class="widget-title" style="color:#fec20b;">S ...

Can someone guide me on incorporating bluebird promises with request-extensible?

I'm interested in utilizing the bluebird library to create a promise-based asynchronous web client. Currently, I have been using the request-promise package for this purpose. To get started, I simply include the following lines of code at the beginnin ...

Implementing Vue data binding with JavaScript objects

I have been tinkering with a JavaScript object that I want to connect with a Vue view. When I trigger a function to update this JavaScript object using AJAX, I expected Vue to automatically sync up and refresh the view. However, it seems like the binding ...

The ForEach function does not execute actions on every individual object, but rather only once

I am currently developing a Deck building application for a card game. In addition, I have set up a database to manage the cards that I sell and play with. The deck builder tool I created allows me to deplete the stock of sellable cards when adding them to ...

Troubles encountered while processing STL file readers

Utilizing STLLoader.js, I am able to render components successfully, however, they all appear with one uniform color which does not resemble real-world components. The image above showcases my implementation in Three.js using STLLoader.js (Binary STL file ...

The Plupload internal version seems to be incorrect. The file is labeled as 2.3.9, however, the actual version within the file is 2.3

We recently identified a security vulnerability issue with plupload 2.3.6 being deemed as vulnerable. To address this, we downloaded version 2.3.9 from the official Plupload website here: Upon inspection, we found that the zip file is labeled as 2.3.9, bu ...

The input field will be in a read-only state if it contains a value from the database. However, it will be editable if the value

Hello everyone, I am a newcomer to this community and would greatly appreciate your help. I am encountering an issue with the following lines of code: <input type="text" class="form-control" id="fines" name="fines&quo ...

JavaScript - Marking selected text: What are the options?

I am looking to implement a feature in JavaScript (without jQuery) that will allow me to highlight selected text with control points or markers (left and right). These markers should function similar to those on mobile phones, allowing me to extend the sel ...

Node.js Project Using a Specific URL and Parameter

Two things are on my mind: 1. I'm trying to set up my project's URL as 127.0.0.1:8080/param=id, but I've been unsuccessful so far despite attempting the following: app.get('/param=id', function(req, res) { console.log(req.param ...

Use yarn to install both devDependencies and dependencies simultaneously

Can yarn be used to install devDependencies and dependencies simultaneously? For instance, if I need to install react as a dependency and webpack as a dev dependency. Typically, I would have to execute two separate commands like shown below: yarn add reac ...

Unexpected problem discovered with Firefox and JqueryUI - content is misaligned within the dialog box

I seem to be having an issue with a dialog that I recently set up. I've been working with jqueryUi for quite a while so I'm not sure why I can't figure this out. When using Firefox, I noticed that the dialog opens and closes when clicking " ...

What is the best way to create a Laravel object for use in JavaScript in a Laravel Blade?

please add description hereI am looking to obtain an object with this particular style var zoz2= { "11-30--0001": "<a href=\"https:\/\/www.dooz.ps\/p\/107229\" >\u0625\u0637\u0644\u0627& ...

Evolving characteristics of Bootstrap popover

I am currently working on a text field and button setup where I have implemented a popover feature using Bootstrap. This is the code snippet I am using: function displayPopover() { $("#text").popover("show"); } The popover appear ...

The CSS grid-template-area feature is not functioning properly in web browsers

Struggling with creating a responsive CSS grid layout for different screen sizes. I want to have five divs on desktop screens and adjust the layout for smaller screens. As a newbie in web development, I'm finding it challenging to get it right. .fir ...

What is the best way to implement next and previous buttons in a slideshow using code?

Looking to enhance my slideshow by replacing the standard "Next" and "Previous" text buttons with custom JPEG images I've created. Anyone familiar with the steps needed to make this switch in the HTML code? Current HTML code in use: <body sty ...

Incorrect handling of Unix timestamps in AngularJS

I'm facing an issue with timestamps. Let me explain - I have a timestamp coded as 1378028575, which corresponds to Sun, 01 Sep 2013 09:42:55 GMT according to this website. The problem arises when I attempt to format this timestamp using Angular's ...

creating a table displaying data in a horizontal format sourced from ajax/json transformation

I am currently working on a piece of code that retrieves a list of IDs from local storage and compares them to IDs in a JSON file. If there is a match, the corresponding data is displayed in a table. However, I am facing an issue with my table layout as i ...