Utilize jQuery to display a list of defined CSS classes based on a regular expression, implementing a targeted CSS strategy to prevent any

I have defined a set of CSS classes in app.css:

.eventcolor-1{background:rgba(249, 115, 0);}
.eventcolor-2{background:rgba(14, 48, 71, 0.99);}
.eventcolor-3{background:rgba(16, 130, 140, 0.99);}
.eventcolor-4{background:rgba(41, 91, 167, 0.99);}
.eventcolor-5{background:rgba(148, 172, 60, 0.99)}
.eventcolor-6{background:rgba(252, 195, 20, 0.99);} 

In jQuery, I am looking for a method to extract all the .eventcolor-* classes that are currently available and add them to an array.

An existing solution for this issue can be found at:

function getClassNamesByPattern(pattern) {
    var pattern = "eventcolor-*";
    var selectors = {};

    for (var i = 0; i < document.styleSheets.length; i++) {
        var classes = document.styleSheets[i].rules || document.styleSheets[i].cssRules;
        for (var x = 0; x < classes.length; x++) {
            if (undefined !== classes[x].selectorText && null !== classes[x].selectorText.match(new RegExp('\\.' + pattern.replace(/([^\s])\*, '$1[^ ]+'), 'g'))) {
                selectors[classes[x].selectorText] = classes[x].selectorText;
            }
        }
    }

    return Object.keys(selectors);
}

However, this approach triggers a Security Error in Firefox since it scans through unnecessary CSS files. All I want is to target my custom style file app.css.

SecurityError: The operation is insecure.

Is there a secure way to limit the search to only a specified CSS file?

Answer №1

If you want to filter out stylesheets within a loop, you can utilize the StyleSheet.ownerNode property of the CSSStyleSheet objects that you are iterating through.

Assuming you have included your stylesheet as a <link>, the code snippet may appear like this:

function findClassesByPattern(pattern) {
    var pattern = "eventcolor-*";
    var foundClasses = {};

    for (var i = 0; i < document.styleSheets.length; i++) {
        var stylesheet = document.styleSheets[i];
        if (typeof stylesheet.ownerNode !== 'undefined') {
            var ownerNode = stylesheet.ownerNode;
            if (typeof ownerNode.tagName === 'string' && ownerNode.tagName.toLowerCase() === 'link' && ownerNode.rel === 'stylesheet') {
                var href = ownerNode.href;
                if (!href.match(/\/app\.css$/)) {
                    continue;
                }
            }
        }
        var classes = stylesheet.rules || stylesheet.cssRules;
        for (var x = 0; x < classes.length; x++) {
            if (undefined !== classes[x].selectorText && null !== classes[x].selectorText.match(new RegExp('\\.' + pattern.replace(/([^\s])\*/, '$1[^ ]+'), 'g'))) {
                foundClasses[classes[x].selectorText] = classes[x].selectorText;
            }
        }
    }

    return Object.keys(foundClasses);
}

Answer №2

Here is a simple method that I discovered:

document.styleSheets[i].href holds the title of the CSS file that is currently being reviewed.

By using

document.styleSheets[i].href.indexOf("app.css") != -1
, we can verify if "app.css" is included in the stylesheet.

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

Tips for transferring the name field to a different page upon clicking

There are two pages in my project - the first one is called ItemMenuPage and the second one is called CartPage. The functionality I am trying to achieve is that when a user clicks on any item name on the ItemMenuPage, it should navigate to the CartPage, wi ...

Guide on adding CSS3 ribbons to elements on both sides

I recently came across a tutorial that teaches how to create a CSS ribbon. However, after following the tutorial, I found that the ribbon only appears on one side of the element. This has left me wondering if it's possible to have the ribbon display o ...

Retrieving user input in a JavaScript/React app

I'm currently developing a search feature for my website using Algolia. When the user types in their search term, the results are updated to show relevant matches as they go. Here is an example below of what I am working on: https://codesandbox.io/s ...

Using Bootstrap 3 to implement various grid systems within a single website

For a current project I am working on, my goal is to fill the entire .container with 7 columns within my grid system. To achieve this, I plan on adjusting the Less variable (@grid-columns) before compiling a bootstrap.css file at http://getbootstrap.com/cu ...

What is the best way to alphabetically arrange an array of names in a JavaScript.map?

I am attempting to alphabetically sort an array of first names using JavaScript map function. Additionally, I aim to remove the "undefined" row from the final results: function contacts_callback(obj) { var contactinfo = obj.contacts .filter( ...

AWS Amplify-hosted Nuxt applications are resilient to errors during the build process

My website is built using Nuxt js and hosted on AWS Amplify. I've encountered a major issue where the website still gets generated successfully even when there's a failure in the nuxt generate command (like a JavaScript error in my code). Below i ...

Converting JSON to JavaScript Date using UTC time

I am struggling with formatting the dates in a JSON object to work with highcharts. The JSON looks like this: [ [ "26-Sep-14", 10 ], [ "29-Sep-14", 75 ] ] Highcharts requires dates to be in the format Date. ...

Tips for arranging images of varying heights on separate lines so they appear cohesive as a group

I've been working with masonry.js but I'm still not achieving the effect I want. Javascript:` var container = document.querySelector('#container'); var msnry = new Masonry( container, {columnWidth: 200, itemSelector: '.item' ...

Creating an Angular table using reactive forms: a step-by-step guide

After reviewing the HTML snippet provided below, it is evident that there is a table with looping through mat cell using *matCellDef="let model". Inside each cell, there are input fields which are reactive forms. Each row or cell needs to have it ...

Guidelines on declining a pledge in NativeScript with Angular 2

I have encountered an issue with my code in Angular 2. It works fine in that framework, but when I tried using it in a Nativescript project, it failed to work properly. The problem arises when I attempt to reject a promise like this: login(credentials:Cr ...

Hover and focus effects of the main navigation menu in Semantic UI CSS

I seem to be having trouble styling my navbar with semantic-ui. I want to make changes to the color and background-color on hover and when focused. However, no matter what I try, the hover effect just won't work. I was only able to achieve it using jQ ...

The input box is not properly filled with the complete string using protractor sendKeys

[HTTP] --> POST /wd/hub/session/ffcd7072-9f96-45cb-a61d-ec53fc696b56/element/0.9513211246393813-32/value {"value":["1","0","0","0","1"],"text":"10001"} My JavaScript code snippet: this.zipcode = element(by.model('personalInfo.zipcode')); t ...

Revolutionizing Interaction: Unveiling the Power of Bootstrap 3

Would you be able to assist me in customizing buttons to resemble a typical dropdown link? <div class="dropdown"> <button class="btn dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown">Dropdown <span class="caret"&g ...

Not quite sure about the best way to showcase the results // using JavaScript

My code is posted below. I am trying to achieve a functionality where, upon clicking the 'Calculate Price' button, the results showing the number of cars, type of cars, and their respective prices are displayed beneath the button. Despite this be ...

Is it possible for browser sync to replace a CSS file hosted on a CDN upon injection?

Trying to solve a dilemma with my Shopify theme. Working on my Shopify theme, I find it frustrating that I have to constantly save my CSS changes, switch tabs, and reload the browser to see updates. While I know about the theme gem, it doesn't provid ...

Incorporating a dynamic fill effect into an SVG pie chart

I am looking to animate a pie chart with a variable value that is unknown upon loading. Assuming I fetch the value promptly and convert it into a rounded percentage : var percentage = Math.round(sum * 100 / total); Next, I place this value here : <di ...

Troubleshooting WordPress <?php body_class(); ?> Problem

After successfully integrating my theme into WordPress, I decided to add WooCommerce to create a shop. However, I encountered an issue where the styles of WooCommerce were not appearing properly. Upon researching, I discovered that the root cause was the a ...

Identifying and implementing page language in nextJS: Solving the ReferenceError "window is not defined" issue

I am currently working on developing a website that can automatically detect the user's country and set the language accordingly. In React, I usually achieve this by using window.navigator.language. Here is a snippet of the code: import * as pt from ...

CSS3 Icon: the content being placed is not consistently positioned

I'm utilizing CSS3 to create icons, and everything was going smoothly until I encountered an issue with a simple design. My goal is to have an exclamation mark centered inside a circle, but its position appears inconsistent. At times, it seems slightl ...

What are some techniques for obtaining the second duplicate value from a JSON Array in a React JS application by utilizing lodash?

Currently, I am tackling a project that requires me to eliminate duplicate values from a JSON array object in react JS with specific criteria. My initial attempt was to use the _.uniqBy method, but it only retained the first value from each set of duplicat ...