To grab a specific CSS attribute from a stylesheet using JavaScript

I am looking for a way to extract the value from a CSS file using a JavaScript function.

Take a look at my code snippet below:
HTML file ->

    <link rel="stylesheet" type="text/css" href="test_css.css" />
    <script type="text/javascript">
    function loadFunc(){ 
    ## need code here
    ## alert(left);
    }
    </script>

CSS file ->

    .outer .inner
    {
    left: 30pt;
    top: 20pt;
    }

Note: I only require the specific property value from the CSS, not the entire text. Is there a predefined function that can help me achieve this?

For instance, I want to retrieve the value associated with the key "left" in the CSS file. The expected output should be "30pt".

Answer №1

Executing this function with the specified attributes will result in the expected output.

    function fetchStylePropertyValue(prop, selector, stylesheet) {
      var stylesheets = typeof stylesheet !== 'undefined' ? [stylesheet] : document.styleSheets;
      for (var index = 0, len = stylesheets.length; index < len; index++) {
        var currentSheet = stylesheets[index];
        if( !currentSheet.cssRules ) { continue; }
        for (var j = 0, k = currentSheet.cssRules.length; j < k; j++) {
          var cssRule = currentSheet.cssRules[j];
          if (cssRule.selectorText && cssRule.selectorText.split(',').indexOf(selector) !== -1) 
             return cssRule.style[prop];            
         }
       }
      return null;
     }

    var textColor = fetchStylePropertyValue('color', '.classproperty'); // applicable to all stylesheets

Answer №2

To apply CSS to elements, utilize jQuery along with the .css function. Additional resources can be found here: http://api.jquery.com/css/

Note: Ensure that you have the specified style visible on your webpage before using this method. If the style is not present, consider creating a hidden div for the CSS selector to target.

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

Node.js utilized for conducting anti-virus scans on server-bound files prior to uploading

Is there a way for me to scan files that are submitted as request payloads to check if they contain potential viruses? For example, if someone tries to upload a txt file with the EICAR virus signature, I want to be able to scan it and reject it if it is in ...

AccessMediaStream - camera direction

My current setup involves using an Android tablet and GetUserMedia to capture images in my program. It seems that by default, GetUserMedia uses the front camera. How can I set the rear camera as the default instead? Below is the code snippet I am using w ...

Send a variety of jQuery element selectors to a function

myFunc() is connected to the document scroll event, resulting in frequent calls. To optimize performance, I intend to store HTML selections in variables and then pass them to the function. However, upon running the code snippet below, an error appears in t ...

Adding an AngularJS directive dynamically that utilizes a $http request for fetching data

Currently facing an intriguing issue, I am attempting to create something like this: input key 1 , input value 1 input key 2 , input value 2 < button to add more > < submit button > Essentially, a user can click submit and send a Get req ...

Why am I seeing numbers in the output when I log the data from the res.write(data) function in Node.js?

While working with Node.js on my Raspberry Pi, I encountered an issue where reading a local file 'test.html' resulted in hex output instead of the expected HTML format. Can someone explain why this might be happening? Additionally, I am aware tha ...

How is it possible for a parameter sent via GET to persist through multiple requests?

Within my JSP file, I have implemented an HTML form that utilizes the GET method to send data to my servlet. <form method="GET"> <input name="cmd" type="hidden" value="firstValue"/> ..... </form> Upon triggering another form ...

Organize angularjs ngRepeat with updated data outcomes

I am facing a situation where I need to display results from different ajax sources, but they are loaded asynchronously. The problem is that I want the results to be sorted alphabetically once they are all loaded. ngRepeat doesn't sort them correctly ...

Cursor vanishes until mouse movement detected (Chrome browser)

In the HTML page I created, the mouse cursor is initially set to none. However, there are certain circumstances where I need it to switch to crosshair. The issue I am facing is that the cursor does not appear unless the user moves the mouse. If the mouse r ...

Oops! It seems like there was an issue trying to access properties that are undefined while reading 'pipe' in Angular12

I encountered an issue when trying to send an AJAX request, displaying the following error message: ERROR TypeError: Cannot read properties of undefined (reading 'pipe') This error occurred in the ajax-loader.interceptor.ts class export class A ...

Navigating with React in ES5

My email addresses are "[email protected]" and "[email protected]". I am facing an issue with the following minimal example code: var React = require('react'); var ReactDOM = require('react-dom'); var Router = require(' ...

Unable to retrieve field values from Firestore if they are numeric rather than strings

I need to display this information in a list format: li.setAttribute('data-id', updatesArgument.id);//'id' here unique id Example 1 name.textContent = updatesArgument.data().count;// Works if String Example 2 let i=1; nam ...

What are some ways to implement querySelectorAll in conjunction with htmx?

I'm currently using htmx, an amazing library with a small issue that I'm struggling to resolve. htmx utilizes querySelector to find elements for swapping or updating, for example with hx-swap="...", hx-target="...". How can I use querySelectorAll ...

Incorporating PHP in JS/jQuery AJAX for creating unique odd and even conditional layouts

My PHP code includes a loop that changes the layout of elements based on whether the $count variable is odd or even. For odd counts, an image appears on the left and text on the right. For even counts, it's the other way around. To load content dynam ...

Challenges with exporting dynamically generated divs using jspdf in an Angular 2 project

I have been utilizing the jspdf library to print div elements in my current project. But I recently discovered an issue where dynamic content within a div is not being printed correctly. Specifically, when incorporating simple Angular if statements, jspdf ...

Error: Property '$filter' is not defined and cannot be read

Whenever a user clicks on a link, I display the json object on the UI. However, an exception is being thrown with the following message: TypeError: Cannot read property '$filter' of undefined Check out the demo here: http://plnkr.co/edit/5NOBQ3 ...

Trigger the execution of a Python script through a webpage with just the click of a button

I have a small web interface where I need to control a Python script that is constantly gathering data from a sensor in a while loop. Ideally, I would like the ability to start and stop this script with the click of a button. While stopping the script is s ...

Implementing the SendOwl License API for theme licensing

Currently developing a Shopify theme for sale and exploring licensing options Considering using SendOwl's API for licenses - Shopify themes support html/css/js/liquid, no server-side code, so JavaScript is required. Can the SendOwl API be used to v ...

Tips for linking two tus servers

Trying to find a solution for uploading files with resume capability to Cloudflare using the tus enabled API. The challenge is ensuring that credentials remain secure, which prevents direct uploading from the browser to Cloudflare. This requires implementi ...

What is the best way to incorporate two range sliders on a single webpage?

I recently started using rangeslider.js on my webpage. I wanted to convert two input fields into range sliders, so I began by converting one successfully. Initially, the HTML code looked like this: <div class="rangeslider-wrap"> <input type=" ...

Enhance the current MultiSelect object by incorporating JQuery MultiSelect

Is there a way to detect changes on a JQuery MultiSelect in order to trigger an update elsewhere? The typical javascript onchange method does not seem to work because the select itself does not change. However, I came across a method called "beforeclose" t ...