Acquire the CSS percentage value using jQuery

At this moment, the width() function in jQuery as well as its variations all return values in pixels. The same applies when using the css('width') method.

I have elements that are styled in external .css files, and there is no way for me to determine if they are styled in percentages or pixels. If an element has a width set in percentage or no width at all, I need to retrieve a percent value.

For instance, consider the following:

.seventy { width: 70%; }
.pixels { width: 350px; }

<div class="seventy"></div>
<div class="pixels"></div>
<div class="regular"></div>

In this scenario, these would be the desired outcomes:

$('.seventy').method() //=> '70%'
$('.pixels').method() //=> '350px'
$('.regular').method() //=> '100%' due to default behavior of block elements

Is there a built-in method in jQuery that can help me achieve this outcome? Alternatively, is there a custom approach that could be taken?

Answer №1

To retrieve style information from a CSS file, you can utilize the document.stylesheets method to locate a specific style rule. It is important to note that this approach will only provide the parsed style after it has been interpreted by the browser. If you require the raw unaltered CSS as written in the file itself, then direct parsing of the file content is necessary rather than relying on document.stylesheets.

It should be acknowledged that this code is outdated and unverified, hence results may vary. The functionality with inherited values or complex selectors is uncertain.

// CODE SNIPPET TO EXTRACT CSS
var CSS = function () {
    var _sheet;
    var _rules;
    function CSS() {
        _sheet = document.styleSheets[0];
        if (_sheet.rules) {
            _rules = _sheet.rules; // For IE
        } else {
            _rules = _sheet.cssRules; // Compliant with standards
        }
  
      this.find = function (selector) {  
          var i = _rules.length;
          while(i--){
              if (_rules[i].selectorText == selector) {
                  break;
              }
              if(i==0){break;}
          }

          return _rules[i].style;
      }

        this.set = function (foo) {
            // Functionality yet to be implemented
        }
    };

    return new CSS();
};
// Initialization
var css = new CSS();
// Display output in console log.
console.log(css.find(".regular")); // Pay attention to the empty width property
// Update elements based on the findings
document.querySelector(".seventy").innerHTML = css.find(".seventy").width;
document.querySelector(".pixels").innerHTML = css.find(".pixels").width;
document.querySelector(".regular").innerHTML = css.find(".regular").width;
// Additional tests
document.getElementById("a").innerHTML = css.find("body").color;
document.getElementById("b").innerHTML = css.find("h1").color;
document.getElementById("c").innerHTML = css.find("h1").width;
document.getElementById("d").innerHTML = css.find(".notInDom").color;
body {
  font-family: sans-serif;
  color: black;
  background-color: #cccccc;
}

h1 {
  color: blue;
  font-size: 1.5em;
  font-weight: 400;
  width: 70%;
}

.seventy, .pixels, .regular {display: block; border: 1px solid red;}

.seventy {display: block; border: 1px solid red; width: 70%; }
.pixels { width: 350px; }
.regular {}

.notInDom {
  color: red;
}
<h1>Accessing Style Attributes Directly from the CSS File.</h1>

<div class="seventy"></div>
<div class="pixels"></div>
<div class="regular"></div>

<ul>
  <li>css.find("body").color = <span id='a'></span></li>
  <li>css.find("h1").color = <span id='b'></span></li>
  <li>css.find("h1").width = <span id='c'></span></li>
  <li>css.find(".notInDom").color = <span id='d'></span></li>
</ul>
<p>Please note that this feature is still under development and lacks comprehensive testing. The implementation is rudimentary and has limitations.</p>

Answer №2

function fetchStyle(selector) {
var styleSheets = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
for (var i = 0; i < styleSheets.length; i++) {
if (styleSheets[i].selectorText == selector) {
(styleSheets[i].cssText) ? alert(styleSheets[i].cssText) : alert(styleSheets[i].style.cssText);
}
}
}
fetchStyle('.test');

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

Laravel Ajax 419 Error Occurring in Production Environment, Yet Absent in Local Development, with No Trace in /storage/logs/laravel

I encountered a 419 Error code while submitting my AJAX request in my project. This error is related to the CSRF Token not being passed or invalid. Recently, I implemented a "maintenance mode" on my project that restricts access to the front end by displa ...

Angular 8 allows for dynamic updates as users provide input and make selections with check marks

When using Angular 8, if a user inputs "$10" and then clicks on it (using the OnClick event), the box below should be updated with the user input and the entire box should be selected like the example shown in the picture. I would greatly appreciate any t ...

Generate a new text document in Google Drive using JavaScript

Currently, I am working on a web application using JavaScript and jQuery. My goal is to extract notes from an input text field on my webpage and save that information in a text file on Google Drive. Although I have successfully managed to sign in and autho ...

Issues with Twitter Bootstrap Tabs not functioning correctly on Ruby on Rails with HAML

I am facing an issue with twitter bootstrap tabs in my (HAML) ruby on rails project. Although the tabs are appearing, the content does not change when I click on different tabs. Additionally, some unexpected statements are showing up at the bottom of the f ...

PHP script does not seem to be processing the jQuery AJAX request sent via POST

I just created my very first PHP page with a search form: <form action="#" class="form-inline" id="form_srch"> <input type="text" id="toSearch" name="toSearch" placeholder="Enter Application Number" class="form-control" style="width:250px" requ ...

Can you tell me the distinction between using RemoteWebDriver's executeScript() and Selenium's getEval() for executing

Can you explain the distinction between these two pieces of code: RemoteWebDriver driver = new FirefoxDriver(); Object result = driver.executeScript("somefunction();"); and this: RemoteWebDriver driver = new FirefoxDriver(); Selenium seleniumDriver = ne ...

What is the best way to organize controls on my website?

My web page controls need to be organized in the specific layout below: Header Left Content - Main Content - Right Content Footer Is there a control available that can assist me with achieving this layout? I prefer not to use a table since it may not b ...

Utilizing the Twitter API 1.1 to retrieve a list of tweets

As I work on updating my CMS component, I am incorporating integration with the Twitter API to fetch and showcase a list of tweets related to a user or search query. I have chosen to utilize the Twitter Restful API v1.1 as the 1.0 version is set to be disc ...

Yearly Grouping with MongoDB's Aggregate Framework

I've been experimenting with the aggregate function to group date fields by year: db.identities.aggregate([ { $group : { _id : { year : {$year : "$birth_date"}}, total : {$sum : 1} } } ]) However, I encountered a c ...

Creating dynamic forms using JQuery Ajax is an innovative way to enhance

I am working on a form that is generated dynamically and I need to send it to a PHP file using $.ajax. Can you provide guidance on how to achieve this and what should be assigned to the data property? ...

The PHP code doesn't display the slider, whereas it appears on the HTML page

Creating a shortcode for a slider that displays WordPress featured posts and allows users to view details of each post through a hidden div. The slider is inspired by the one on w3schools, where you can find the code and test it online at this link: https: ...

Is there a way to prevent the removal of CSS files from a module when deploying a Next JS API to Vercel?

Is there a way to access a css file from a node_modules package in order to generate swagger documentation within an endpoint using the Next API? I have noticed that tree shaking is removing the css files from the swagger-ui-dist package. How can this be ...

The delete button using jQuery Ajax is successfully working, however, the data is not being removed

I am having an issue with the delete button. It seems to be working fine as it displays 'record deleted successfully', but the record is not actually being deleted from the table and database. Below is the code I am using for the delete query: & ...

Encountering a Sails.js malfunction while attempting to modify and save a function

Encountering an issue while attempting to set up edit and update functions using Sails.js. The error occurs upon clicking the edit button. <html> <body> <table> <thead> & ...

The cakePHP time dropdown feature lacks customization options

When viewing my form in CakePHP, I noticed that the time select dropdown appears differently in Chrome compared to Firefox. In Firefox, there are 3 arrow buttons attached to each dropdown, whereas in Chrome it looks different. I want to hide the arrow but ...

How to customize the hover background color for multicolored series in Highcharts?

Highcharts offers a background color for all columns in a series. The hover color across themes is consistently a light blue (155, 200, 255, .2). To see an example, visit: http://jsfiddle.net/38pvL4cb/ If you look at the source code, Highcharts creates a ...

When using ReactJS, the state does not properly update during onChange events if the initial state is derived from props

Initially, I have set the value of my Form Input to be equal to the initial state obtained from my props. However, upon typing in the Form Input and triggering the onChange event with a handleChange function, the value does not change as expected. handl ...

Transform CSS into React styling syntax

I am having trouble converting CSS code from an HTML template for text input into a React project. I am not a CSS expert, and I am encountering some syntax errors. Can someone help me fix this issue? I have included the CSS code, app.js file, and error ima ...

Integration of Tailwind CSS and VueJS single file components within the VS Code environment

Is there a way to configure Tailwind CSS and VS Code in order to prevent errors related to at-rules and empty tag errors inside a VueJS single file component (vue-cli)? <template> ... </template> <style lang="scss"> body { // } ...

html issue with d3.js rendering images: works in firefox, but not in chrome

I am currently experiencing an issue with a D3 graphic that runs successfully in Firefox but fails to render in Chrome when using an HTML and JSON file. Upon checking the console, I see the following error message: d3.v3.min.js:1 Access to XMLHttpReque ...