Retrieve the names of all classes listed in the internal stylesheet

Is there a way to extract the names of all classes defined in an internal stylesheet using jQuery? For example, if I have the following internal stylesheet:

<style  id="custstyle" type="text/css">
            .column{
                font-size:13px;
                font-family:arial, helvetica, verdana, sans-serif;
                font-weight:normal;
                color:rgb(221, 221, 221);
                font-size:13px;
                font-family:arial, helvetica, verdana, sans-serif;
                font-weight:normal;
                color:rgb(221, 221, 221);
            }
        </style>

and calling $('#custstyle').html() or $('#custstyle').text() will return the entire CSS code as shown below:

.column{
                font-size:13px;
                font-family:arial, helvetica, verdana, sans-serif;
                font-weight:normal;
                color:rgb(221, 221, 221);
                font-size:13px;
                font-family:arial, helvetica, verdana, sans-serif;
                font-weight:normal;
                color:rgb(221, 221, 221);
            } 

But what I actually want is to retrieve only the class name .column...

Answer №1

In order to retrieve the CSS selectors, follow these steps:

let content = $('#custstyle').html();
while (content.indexOf('{') != -1) {
    alert(content.substring(0, content.indexOf('{')));
    content = content.substring(content.indexOf('}') + 1);
}

For a live demo, check out this Fiddle: http://jsfiddle.net/5gzxk/

Answer №2

An unconventional method for displaying all selectors in a style sheet is:

for(let i = 0; i < document.styleSheets.length; i++) {
   let stylesheet = document.styleSheets[i];
   for(let j = 0; stylesheet.cssRules && j < stylesheet.cssRules.length; j++) {
      let rule = stylesheet.cssRules[j];
      console.log(rule.selectorText);
   }
}

Answer №3

Give this a try:

let elements = document.querySelectorAll('body *');
let uniqueClasses = [];
for (let element of elements) {
    for (let className of Array.from(element.classList)) {
        if (!uniqueClasses.includes(className)) {
            uniqueClasses.push(className);
        }
    }
}

Note: If you need to convert internal styles to inline CSS, consider using the following approach:

let elements = document.querySelectorAll('body *');
let classObject = {};
for (let i = 0; i < elements.length; i++) {
    let element = elements[i];
    let classesArray = Array.from(element.classList);
    classObject[i] = {
        node: element,
        classes: classesArray
    };
}

Answer №4

There might be some potential in utilizing this information. If you are interested in obtaining the selectors, you can refer to the sheet property of the HTMLStyleElement:

var rules = $('#custstyle').prop('sheet').cssRules;
var selectors = $.map(rules, function(rule){
     return rule.selectorText;
});

The variable selectors now holds an array of selectors.

http://jsbin.com/iQEvuMeT/1/

If you wish to retrieve both the selectors and their specific styles:

var rules = $('#custstyle').prop('sheet').cssRules;
var results = $.map(rules, function(rule) {
    var o = {};
    $.each(rule.style, function(_, item) {
       o[item] = rule.style[item];
    }); 
    return { selector: rule.selectorText, styles: styles };
});

Now, the variable results consists of an array of objects. To apply inline styles to elements, you can utilize the css() method. Since it accepts an object, you can write the following code:

$.each(results, function(_, v) {
   $(v.selector).css(v.styles);
});

This will result in:

<div class="column" 
     style="font-size: 13px; font-family: arial, helvetica, verdana, sans-serif; font-weight: normal; color: rgb(221, 221, 221);">
</div> 

Although it may initially seem unnecessary and repetitive, there could be scenarios where this approach proves beneficial!

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

Using Bootstrap's fourth version grid system

Struggling with creating a layout on bootstrap4? Here's a code snippet to help you out. Thank you in advance! <div class="col-8"> <a href="#"> <div class="card"> <img class="card-img" src="img.jpg"> ...

The `div` element automatically starts on a new line rather than expanding vertically

Check out my code here: http://jsfiddle.net/sfhs6ra1/ I'm facing an issue where I want the title of post #2 to be aligned next to the thumbnail image, taking up more vertical space instead of moving to a new line. Any suggestions on how I can achiev ...

Combine the text value from a textbox and the value from a checkbox into a single

I'm trying to solve a challenge regarding appending values from text fields (excluding empty ones) and checkboxes in a specific order to form a string. It should be in the format: name|T|F_name|F|F. Once I've created this string, I plan to send i ...

Having trouble with the Ajax loop callback method functioning properly for each individual request

While working with an ajax each loop, I encountered a problem with the callback function. The success or progress callbacks do not seem to be functioning properly for each request made. The first and second callbacks are failing to execute. entries.forEa ...

"Change opacity smoothly with the FadeToggle feature for a

I have a question that might seem silly, but I can't quite figure it out. How can I extend the duration of the fade effect? window.switchIn = function() { $('.red').fadeToggle(function(){ $('.blue').fadeToggle(function() { ...

Connect to dynamically generated div on separate page

I am facing an issue with my navigation bar drop down menu that displays event titles fetched from the database. I want users to be able to click on a specific event and have the page scroll to the dynamically generated content for that event. However, it ...

Is it possible to create clickable titles in highcharts that also interact with bootstrap popovers?

Hello, I'm trying to figure out how to turn the title in highcharts into a clickable link that works with bootstrap's popover feature. You can find an example of what I'm working on here: http://jsfiddle.net/287JP/4/ $(function () { ...

Creating a div that expands to fill up the remaining height within a flex-child

I'm facing a challenge with a flex container that contains flex children. Within each flex child, there are two stacked divs, the first of which has an unknown height. My goal is to make the second div fill the remaining height available. I've be ...

Having difficulty retrieving JSON data using Jquery

After receiving a JSON string as a response from the server, I encountered an issue when trying to access the objects within the response, only to receive an "undefined" message. Here is the AJAX request being made: $.ajax({ url: 'somefi ...

What could be the reason that setting document.body.style.backgroundImage does not apply to the body element itself?

Consider an HTML document with the given CSS: body { background: url("http://via.placeholder.com/200x200"); width: 200px; height: 200px; } Why does the following code not display the background image URL when executed: console.log(document.body. ...

Bootstrap 5 utilizes an 8-column system specifically designed for tablets, while defaulting to a 12-column system for both desktop and mobile versions

Currently, I am utilizing the Bootstrap grid system with its 12-column setup, which is working well. However, my designer has requested that I make the Tablet view an 8-column system, with each column taking up 100% of the width and no gutters in between. ...

"Is there a way to implement the functions of adding, editing, and deleting data in

When attempting to display a table using jQuery DataTable, I would like to add edit and delete buttons at the last column of each row. How can I ensure that the database is updated with every edit and delete action? Ajax Request Example: //Ajax to get id ...

Create dynamic cells for CSS grid using JavaScript

I have been manually generating grid cells in a specific pattern by copying and adjusting <div> elements. Although this method works, I am interested in creating an algorithm that can automatically generate the desired layout. The left box in the exa ...

The canvas surpasses the boundaries of the grid layout

Trying to design a grid layout with 3 columns of content, alongside an .overlay div featuring a particles.js canvas. Having trouble? See my Codepen here: https://codepen.io/radzak/pen/MVQVPQ The goal is for the grid to always occupy 100% of the screen, t ...

Display a div using Ajax by triggering a PHP function

I have a hyperlink that reveals more information based on the value it combines. Whenever I click on this hyperlink, I want to display the corresponding values by opening a div using ajax on the same page. Check out the link below: <a class="dropdown ...

The HTML elements may have identical heights, but visually, one appears larger than the other

The size of the "login to enter chat" button seems to be larger than the messageBox div, despite adjusting padding and margins. What could be causing this issue? Any suggestions on how to fix this design glitch? #chatbox { width: 500px; height: ...

Searching with Jquery Ajax

For my search functionality, I am utilizing ajax jquery js. I found this useful code snippet here: However, I am facing some challenges with the following Javascript code: <script language="JavaScript" type="text/javascript"> <!-- function searc ...

Is there a way to automatically trigger an Anthem.NET button click event upon page load in ASP.NET?

My goal is to initiate the loading of an ASP.NET page followed by triggering a server-side event that will update some HTML on the client side. The event is associated with an Anthem.NET imagebutton control, so the most obvious approach would be to simply ...

Creating lasting placeholder text with gaps between each word

Looking to create a unique text input with static content on the right and editable text on the left https://i.stack.imgur.com/K0YfM.png Any suggestions? ...

Optimal practices for naming divs in XHTML/CSS

Is it acceptable to use spaces in div names like this? <div class="frame header">Some content here</div> Having a space in the name might require separate CSS classes such as: .frame { display: block; } .header { background-color: #efefef; } ...